描述 输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数
例如,1~13中包含1的数字有1、10、11、12、13因此共出现6次示例1 输入: 13 返回值: 6
思路1:暴力循环
就不写了
思路2:按位遍历
https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/submissions/
public class Solution {
public static void main(String[] args) {
int n = 12;
System.out.println(NumberOf1Between1AndN_Solution(n));
}
private static int NumberOf1Between1AndN_Solution(int n) {
int low = 0; //低位
int cur = n % 10; //当前位
int high = n / 10; //高位
int digit = 1; //位数
int res = 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 = high / 10;
digit *= 10;
}
return res;
}
}