File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 剑指上的题目
2
+ // Runtime: 4 ms, faster than 48.35% of C++ online submissions for Number of Digit One.
3
+ // Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Number of Digit One.
4
+
5
+ class Solution
6
+ {
7
+ public:
8
+ int countDigitOne (int n)
9
+ {
10
+ if (n <= 0 )
11
+ return 0 ;
12
+
13
+ // 同样需要注意数据溢出的问题
14
+ long long base = 10 ;
15
+ long long count = 0 ;
16
+ while (n / base > 0 )
17
+ base *= 10 , count++;
18
+ base /= 10 ;
19
+
20
+ long long high = n / base;
21
+ long long res = 0 ;
22
+
23
+ if (high == 1 )
24
+ res += n - high * base + 1 ;
25
+ else
26
+ res += base;
27
+
28
+ res += high * count * (base / 10 );
29
+
30
+ return res + countDigitOne (n - high * base);
31
+ }
32
+ };
Original file line number Diff line number Diff line change
1
+ # Runtime: 32 ms, faster than 89.32% of Python3 online submissions for Number of Digit One.
2
+ # Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Number of Digit One.
3
+
4
+ class Solution :
5
+ def countDigitOne (self , n ):
6
+ """
7
+ :type n: int
8
+ :rtype: int
9
+ """
10
+
11
+ if n <= 0 :
12
+ return 0
13
+
14
+ base = 10
15
+ count = 0
16
+ while n // base > 0 :
17
+ base *= 10
18
+ count += 1
19
+ base /= 10
20
+
21
+ high = n // base
22
+ res = 0
23
+
24
+ if high is 1 :
25
+ res += n - high * base + 1
26
+ else :
27
+ res += base
28
+
29
+ res += high * count * (base / 10 )
30
+
31
+ return res + self .countDigitOne (n - high * base )
You can’t perform that action at this time.
0 commit comments