剑指 Offer 43. 1~n 整数中 1 出现的次数(233. 数字 1 的个数)
题目:
思路:
【1】逐次统计个位、十位、百位......1出现的次数,做和即可
代码展示:
//时间0 ms击败100% //内存38 MB击败90.14% class Solution { public int countDigitOne(int n) { int ans = 0; long base = 1; while(base <= n){ int a = (int)(n / base); int b = (int)(n % base); int cur = a % 10; a = a /10; if(cur > 1){ ans += ((a + 1) * base); }else if(cur == 1){ ans += (a*base + b + 1); }else { ans += a*base; } base *= 10; } return ans; } }