← Home

233. Number of Digit One

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
233

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 233. Number of Digit One, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming.

The notes already sitting in the source point us in the right direction:

  • Math
  • time: O(log_10(n)), space: O(1)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are countDigitOne, memo.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(log_10(n)), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Math
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number of Digit One.
03//Memory Usage: 6.1 MB, less than 27.55% of C++ online submissions for Number of Digit One.
04//time: O(log_10(n)), space: O(1)
05class Solution {
06public:
07    int countDigitOne(int n) {
08        int ans = 0;
09        
10        /*
11        for the example 1234:
12        there are 123(0001,0011,0021,...,1221) +  
13        1(1231) '1' in 'one' position
14        there are 1234/100*10(0010-0019, 0110-0119, 1110-1119) + 
15        10(1210-1219) '1' in 'ten' position
16        there are 1234/1000*100=100(0100-0199) + 
17        100(1100-1199) '1' in 'hundred' position
18        there are 0 +
19        235(1000-1234) '1' in 'thousand' position
20        */
21        
22        for(long long i = 1; i <= n; i*=10){
23            /*
24            (n/(i*10))*i: count of '1' in ith(1-based) position 
25            from 0 to n/(i*10)*(i*10)
26            min(max(n%(i*10)-i+1, 0), i): from n/(i*10)*(i*10)+1 to n
27            */
28            ans += (n/(i*10))*i + min(max(n%(i*10)-i+1, 0LL), i);
29        }
30        
31        return ans;
32    }
33}; 
34
35//DP
36//not understand
37//https://leetcode.com/problems/number-of-digit-one/discuss/254596/My-dynamic-programming-java-solution
38//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number of Digit One.
39//Memory Usage: 6.3 MB, less than 8.98% of C++ online submissions for Number of Digit One.
40class Solution {
41public:
42    int countDigitOne(int n) {
43        /*
44        memo[i]: how many '1' in ith position (1-based)
45        memo[0]: 0
46        memo[1](one digit 0-9): 0*10+1 = 1
47        memo[2](two digits 0-99): 1*10+10 = 20
48        (00-09, 10-19, ..., 90-99)'s 1st digit + 10-19's 2nd digit
49        memo[3](three digits 0-999): 20*10 + 100 = 300
50        (000-099, 100-199, ..., 900-999)'s 1st and 2nd digits + 100-199's 3rd digit
51        */
52        vector<long long> memo(11);
53        int rest = n;
54        long long base = 1;
55        
56        for(int i = 1; rest > 0; i++){
57            memo[i] = memo[i-1] * 10 + base;
58            base *= 10;
59            rest /= 10;
60            // cout << rest << ", " << base << endl;
61        }
62        
63        rest = n;
64        base = 1e9;
65        int index = log10(base)+1;
66        int ans = 0;
67        
68        while(rest > 0 && index >= 1){
69            if(rest >= base){
70                int dividend = rest/base;
71                rest %= base;
72                // cout << "rest: " << rest << ", base: " << base << endl;
73                if(dividend == 1){
74                    ans += memo[index-1] + rest + 1;
75                    // cout << index << ", " << memo[index-1] << ", " << rest << ", " << ans << endl;
76                }else{
77                    ans += memo[index-1] * dividend + base;
78                    // cout << index << ", " << memo[index-1] << ", " << dividend << ", " << base << ", " << ans << endl;
79                }
80            }
81            index--;
82            base /= 10;
83        }
84        // cout << endl;
85        
86        return ans;
87    }
88};

Cost

Complexity

Time
O(log_10(n)), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.