1~n整数中1出现的次数
输入一个整数n,求1~n这n整数的十进制表示中1出现的次数。主要还是一个找规律的题目。
解题思路传送门
public class Offer49 {
public static void main(String[] args) {
int i = new Offer49().numberOf1Between1AndN(21354);
System.out.println(i);
}
public int numberOf1Between1AndN(int n){
if(n <= 0){
return 0;
}
int curr, low, temp, high = n, i = 1, total = 0;
while(high!=0){
// 计算出有几个10^i
high = n / (int)Math.pow(10, i);
// 计算之于10^i的余数
temp = n % (int)Math.pow(10, i); //
// 计算余数的高位
curr = temp / (int)Math.pow(10, i-1);
// 计算余数的低位
low = temp%(int)Math.pow(10, i-1);
if(curr == 1){
total += high*(int)Math.pow(10, i-1)+ low + 1;
}else if(curr < 1){
total += high*(int) Math.pow(10, i-1);
}else{
total += (high + 1) * (int)Math.pow(10, i-1);
}
i++;
}
return total;
}
}