#233
Number of Digit One
HardApproaches
💡
Intuition
Time O(n log n)Space O(1)
The brute force approach involves checking each number from 0 to n and counting how many times the digit '1' appears in each number. It's straightforward but inefficient for large values of n.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter to zero.
- 2Step 2: Loop through each number from 0 to n.
- 3Step 3: For each number, convert it to a string and count the occurrences of '1'.
- 4Step 4: Add the count to the counter.
- 5Step 5: Return the counter.
solution.py9 lines
1# Full working Python code
2
3def countDigitOne(n):
4 count = 0
5 for i in range(n + 1):
6 count += str(i).count('1')
7 return count
8
9print(countDigitOne(13)) # Output: 6ℹ
Complexity note: The time complexity is O(n log n) because converting each number to a string takes log n time, and we do this for n numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.