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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 解题思路
没有思路的题。。。解法来自题解大佬Krahets,题解链接:面试题43. 1~n 整数中 1 出现的次数(清晰图解)
作者:jyd
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3 解决代码
- java代码
class Solution {
public int countDigitOne(int n) {
int digit = 1, res = 0;
int high = n / 10,cur = n % 10,low =0;
while(high != 0 || cur != 0){
if(cur == 0){
res += high * digit;
}
else if(cur == 1){
res += high *digit +low + 1;
}
else{
res+=(high + 1) * digit;
}
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
}
- python3代码
class Solution:
def countDigitOne(self, n: int) -> int:
digit, res = 1, 0
high, cur, low = n // 10, n % 10, 0
while high != 0 or cur != 0:
if cur == 0:
res += high * digit
elif cur == 1:
res += high *digit + low + 1
else:
res += (high + 1) * digit
low = cur * digit +low
cur = high % 10
high = high //10
digit *= 10
return res