Skip to content

Commit 91d1b70

Browse files
committed
Create number_of_digit_one.py
1 parent b1f074f commit 91d1b70

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

Math/number_of_digit_one.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
'''
2+
Number of Digit One
3+
4+
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
5+
6+
Input: 13
7+
Output: 6
8+
9+
Input: 0
10+
Output: 0
11+
12+
=========================================
13+
Count the occurence of 1s for each digit, count the occurance for 1s on each position in the number (example of position xx1x).
14+
Example, if we have 4 digits number, we'll have 4 counts:
15+
1. count of xxx1
16+
2. count of xx1x
17+
3. count of x1xx
18+
4. count of 1xxx
19+
How we could count the occurences?
20+
xxx1
21+
- On the last position, 1 occurs once in each 10 (1, 11, 21, 31, 41...91)
22+
xx1x
23+
- On the second from behind position, 1 occurs 10 times in each 100 (10, 11, 12, 13...19)
24+
x1xx
25+
- On the second from front position, 1 occurs 100 times in each 1000 (100, 101, 102...199)
26+
1xxx
27+
- On the first position, 1 occurs 1000 times in each 10000 (1000, 1001, 1002...1999)
28+
29+
Examples:
30+
Position x1
31+
15 = 2 times
32+
11 = 2 times
33+
10 = 1 time
34+
Position x1x
35+
155 = 2 times
36+
115 = 2 times
37+
105 = 1 tim
38+
39+
That means we'll iterate all the digits, and search for these cases in all the digits:
40+
if the current digit is 0 (in this case we know that Y1xxx didn't happend in the last/current Y)
41+
if the current digit is 1 (will need to count the previous number, Y1xxx -> from 1000 till 1xxx)
42+
(else) if the current digit is greater than 1 (we know that the whole interval Y1000-Y1999 occured)
43+
44+
Time Complexity: O(digitsCount(N))
45+
Space Complexity: O(1)
46+
'''
47+
48+
############
49+
# Solution #
50+
############
51+
52+
def countDigitOne(n: int) -> int:
53+
base = 1
54+
sum = 0
55+
56+
while n >= base:
57+
digit = (n // base) % 10
58+
occurrence = n // (base * 10)
59+
60+
if digit == 0:
61+
sum += occurrence * base
62+
elif digit == 1:
63+
previous = n % base
64+
sum += occurrence * base + (previous + 1)
65+
elif digit > 1:
66+
sum += (occurrence + 1) * base
67+
68+
sum += 0
69+
base = base * 10
70+
71+
return sum
72+
73+
###########
74+
# Testing #
75+
###########
76+
77+
# Test 1
78+
# Correct result => 6
79+
n = 13
80+
print(countDigitOne(n))
81+
82+
# Test 2
83+
# Correct result => 1
84+
n = 2
85+
print(countDigitOne(n))
86+
87+
# Test 3
88+
# Correct result => 92
89+
n = 155
90+
print(countDigitOne(n))
91+
92+
# Test 4
93+
# Correct result => 2
94+
n = 10
95+
print(countDigitOne(n))

0 commit comments

Comments
 (0)