给定一个整数n,返回从1到n的数字中1出现的个数。
例如:
为那么1出现了1次,所以返回1。
为那么1出现的次数为1(出现1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4。
https://blog.csdn.net/yi_Afly/article/details/52012593?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1 这篇博客讲的很清楚,然后要注意10的13次超出了int的表示范围 import java.util.Scanner; /* * * https://www.nowcoder.com/practice/38af9b5a06ea4448ae9b2a488b6a991f?tpId=101&&tqId=33140&rp=1&ru=/activity/oj&qru=/ta/programmer-code-interview-guide/question-ranking * * */ public class Main { public static long count(long n) { if (n < 1) { return 0; } long count = 0; long round = n; long weight = 0; long base = 1; while (round > 0) { weight = round % 10; round = round / 10; count += round * base; if (weight == 1) { count += n % base + 1; } else if (weight > 1) { count += base; } base *=10; } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(count(n)); } }