LeetCode - Number of Digit One

1 minute read

Problem description

description

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

Example:

1
2
3
Input: 13
Output: 6 
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

Analysis

This is a standard digit dp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
    public int countDigitOne(int n) {
        if (n <= 0){
            return 0;
        }
        
        int temp = n;
        int digits = 0;
        while(temp != 0){
            digits++;
            temp = temp / 10;
        }
        
        if (digits == 1){
            return 1;
        }
        
        int[] dp = new int[digits+1];
        dp[0] = 0;
        for (int i = 1; i < digits+1; i++){
            dp[i] = dp[i-1] * 10 + (int)Math.pow(10, i-1); 
        }
        
        int pow = (int)Math.pow(10, digits-1);
        int p = digits;
        
        int res = 0;
        while (n > 0 && p >= 1){
            if (n >= pow){
                int dividend = n/pow;
                n = n % pow;
                if (dividend == 1){
                    res += dp[p-1] + n + 1;
                }
                else{
                    res += dp[p-1] * dividend + pow;
                }
            }
            pow /=10;
            p--;
        }
        
        return res;
    }
}

What to improve

  • be careful about the +1 part in dp array.