本题与LeetCode 233. 数字 1 的个数一致
题目
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
需要注意的地方
- 根据数学推算找结论,可以参考LeetCode上的题解,不得不说,这个大佬太强了,orz
- 在循环后面,随着位数据更新时,出现了一些问题。。。多找找例子,想想为什么
题解
class Solution {
public int countDigitOne(int n) {
// 初始化 ,一开始在个位的情况
int high = n / 10;
int digit = 1;
int curDigit = n % 10;
int low = 0;
int res = 0;
while(high != 0 || curDigit != 0) {
// 根据数学推算得出的结论
if(curDigit == 0) {
res += high * digit;
}
else if(curDigit == 1) {
res += high * digit + low + 1;
}
else {
res += (high + 1) * digit;
}
// digit = digit * 10;
// 这里不能写 n / digit ,例如 n = 100 , digit = 10 , n / digit = 100 / 10 = 1 , 我们知道 100 的十位明明是 0 。。。
// curDigit = ((n / digit) % 10);
// low = n % digit;
// high = high / 10;
digit = digit * 10;
curDigit = high % 10;
low = n % digit;
high = high / 10;
}
return res;
}
}