Number of Digit One

HardMath · Digit DP / Per-Position Counting🧩 Digit DPLeetCode #233 ↗Updated

Problem

Given a non-negative integer n, write out every integer from 0 to n and return how many times the digit 1 appears in total (so 11 contributes two).
Inputn=21Output13 (1, 10, 11×2, 12..19, 21)
Inputn=0Output0
Inputn=2131Output1666

0 ≤ n ≤ 109

Try it yourself

Java
class Solution {
    public int countDigitOne(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Count column by column. For the digit at place value p, split n into high, cur, low: the column shows a 1 exactly high·p times, plus low+1 more if cur == 1, or plus a full p if cur > 1.
PatternDigit DP

Instinct Count numbers in [L, R] (R up to 10^9 or 10^18) whose digits obey a rule - build the number digit by digit with a "still tight to N" flag.

Memory hack Walk the digits on a leash - stay tight to N or break free, and once free you never go back. Remember PTLS - Position, Tight, Leading zero, State.

Open the Digit DP guide →

Approaches

Brute ForceCount Ones in Every Number

Time O(n log n)Space O(1)

Walk x from 1 to n and strip its digits with % 10, adding one for each digit equal to 1.

Java
public int countDigitOne(int n) {
    int total = 0;
    for (int x = 1; x <= n; x++)
        for (int y = x; y > 0; y /= 10)
            if (y % 10 == 1) total++;
    return total;
}

Fine for checking answers; ~1010 digit operations at n = 109.

At a glance

LevelApproachTimeSpace
Brute ForceCount Ones in Every NumberO(n log n)O(1)
BetterDigit DP with a Tight FlagO(10 · L²)O(L²)
OptimalPer-Position FormulaO(log n)O(1)
Common pitfalls
  • Using int for p: p * 10 overflows when n is near 109.
  • Forgetting the +1 in low + 1 (the number with all-zero low part counts too).
  • Memoising tight states in the digit DP — they depend on n's suffix, not just (pos, ones).
Interview tips
  • Write out 0..25 and count ones per column to discover the pattern together.
  • Present the three cases (cur = 0, 1, ≥ 2) as a small table.
  • Mention digit DP as the general tool when the per-digit rule is more complex.
Pattern
Digit counting → “how many times does X appear among 1..n” with n up to 109 or more.
My notes saved in this browser