剑指offer寻找1到n中十进制数中1的个数

题目

输入一个整数n,求1~n这n个整数的十进制表示中1出现的次数。

题解思路

  • 记当前位为cur,且在x的数中,高位部分为high,低位部分为low,即x的十进制表示为 high cur low的表示,例如1234,如果当前位为3,则高位部分为12,地位部分为4,且当前的数字因子digit为101

  • 如果cur = 0

  • 如果cur = 1

  • 如果cur = 其他值

代码

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;
}
java
posted @ 2020-08-31 01:33  珂珂哒  阅读(154)  评论(0)    收藏  举报