Number of Digit One - Problem

Given an integer n, you need to count how many times the digit 1 appears in all non-negative integers from 0 to n (inclusive).

This is a classic mathematical problem that requires careful analysis of digit patterns. For example, if n = 13, we need to examine all numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13. The digit 1 appears in: 1 (once), 10 (once), 11 (twice), 12 (once), 13 (once) = 6 times total.

Goal: Return the total count of digit 1 occurrences across all numbers from 0 to n.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 13
โ€บ Output: 6
๐Ÿ’ก Note: Numbers from 0-13: 0,1,2,3,4,5,6,7,8,9,10,11,12,13. Digit '1' appears in: 1(1 time), 10(1 time), 11(2 times), 12(1 time), 13(1 time). Total = 1+1+2+1+1 = 6
example_2.py โ€” Single Digit
$ Input: n = 1
โ€บ Output: 1
๐Ÿ’ก Note: Numbers from 0-1: 0,1. Only the number '1' contains digit '1', appearing once. Total = 1
example_3.py โ€” Edge Case Zero
$ Input: n = 0
โ€บ Output: 0
๐Ÿ’ก Note: Only number 0 is in range, which contains no digit '1'. Total = 0

Visualization

Tap to expand
Digital Pattern Recognition: Counting 1s EfficientlyExample: n = 3141Split into positions: 3|1|4|1thousands | hundreds | tens | onesOnes Positionhigher = 314current = 1lower = 0Formula: 314ร—1 + 0 + 1Count: 315Tens Positionhigher = 31current = 4lower = 1Formula: (31+1)ร—10Count: 320Hundredshigher = 3current = 1lower = 41Formula: 3ร—100 + 41 + 1Count: 342Thousandshigher = 0current = 3lower = 141Formula: (0+1)ร—1000Count: 1000Total Count of Digit 1315 + 320 + 342 + 1000 = 1977Complexity: O(log n) time, O(1) space๐ŸŽฏ Key Insight: Mathematical patterns eliminate need to check every number!
Understanding the Visualization
1
Position Analysis
For each digit position, analyze the pattern of when digit 1 appears
2
Pattern Formula
Apply mathematical formula based on current digit value (0, 1, or >1)
3
Count Aggregation
Sum up the counts from all positions to get total occurrences
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking every number individually, we can mathematically calculate how many times digit 1 appears at each position by analyzing the patterns in the higher and lower digits.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log n)

We only examine each digit position once, and there are log n positions

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using constant extra space for calculations

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค n โ‰ค 109
  • Time limit: 1 second
  • Space limit: O(1) space preferred for optimal solution
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 25
32.7K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen