[LeetCode] Number of Digit One

233. Number of Digit One

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int countDigitOne(int n) {
int right = n, left = 0;
long res = 0, p = 1;
while(right) {
int num = right % 10;
right /= 10;
res += right * p;
if(num > 1) {
res += p;
} else if(num == 1) {
res += left + 1;
}
left += num * p;
p *= 10;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/12/PS/LeetCode/number-of-digit-one/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.