Enter an integer n and find the number of occurrences of 1 in the decimal representation of n integers.

For example, if you enter 12, 1, and 12, the digits that contain 1 are 1, 10, 11, and 12. 1 appears five times.

Example 1:

Input: n = 12 Output: 5 Example 2:

Input: n = 13 Output: 6

Limitations:

1 <= n < 2^31





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;
        }
        returnres; }}Copy the code

That’s a tough one…