Number of Digit One

HARD

Description

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

 

Example 1:

Input: n = 13
Output: 6

Example 2:

Input: n = 0
Output: 0

 

Constraints:

  • 0 <= n <= 109

Approaches

Checkout 2 different approaches to solve Number of Digit One. Click on different approaches to view the approach and algorithm in detail.

Brute Force Approach

Iterate through all numbers from 1 to n and count the number of 1's in each number.

Algorithm

  1. Initialize count = 0
  2. Loop from i = 1 to n
  3. Convert i to string
  4. Count '1's in the string
  5. Add count to total
  6. Return total count

For each number from 1 to n:

  1. Convert the number to string
  2. Count the occurrences of '1' in the string
  3. Add the count to total
public int countDigitOne(int n) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        String num = String.valueOf(i);
        for (char c : num.toCharArray()) {
            if (c == '1') {
                count++;
            }
        }
    }
    return count;
}

Complexity Analysis

Time Complexity: O(n * log n) - where n is the input number and log n is for converting each number to string and counting 1'sSpace Complexity: O(log n) - space needed to store the string representation of numbers

Pros and Cons

Pros:
  • Simple to understand and implement
  • Works for small inputs
Cons:
  • Very inefficient for large numbers
  • Time complexity is high
  • Not suitable for the given constraints

Code Solutions

Checking out 4 solutions in different languages for Number of Digit One. Click on different languages to view the code.


Video Solution

Watch the video walkthrough for Number of Digit One



Patterns:

MathRecursionDynamic Programming

Subscribe to Scale Engineer newsletter

Learn about System Design, Software Engineering, and interview experiences every week.

No spam, unsubscribe at any time.