Skip to content
Problem 233 · LeetCode 233(opens in a new tab)

Number of Digit One

HardMath

You are given a whole number n. Write out every number from 0 up to and including n, and count how many times the digit 1 appears in all of them together.

A number with several 1s counts each one: 11 adds two, 111 adds three.

Example 1

Input:  n = 215
Output: 148
Why:    22 ones in the ones place, 26 in the tens, 100 in the hundreds
2 more examples and the constraints

Example 2

Input:  n = 5
Output: 1
Why:    only the number 1 has a 1

Example 3

Input:  n = 0
Output: 0
Why:    the only number is 0

Constraints

  • 0 ≤ n ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recurse on the leading digitO(log² n)
  2. Count each place on its ownO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,000,000,000Verdict
Recurse on the leading digitO(log² n)
Passes; harder to derive
Count each place on its ownO(log n)
Best; one short loop

n = the input number; log n is its number of digits. Visiting every number would cost about 10⁹ steps.

Edge cases to test

  • n = 0. No number has a 1: return 0.
  • A 1 digit in n. For n = 111 every place is in the part-way case, where low + 1 matters: the answer is 36.
  • A 0 digit in n. In 2,017 the hundreds digit is 0, so that place only gets its full cycles: high · p.
  • The largest n. 1,000,000,000 has the answer 900,000,001, and p * 10 passes the 32-bit limit.

Common mistakes

  • Looping over every number from 0 to n, which is a billion steps for the largest input.
  • Treating cur = 1 like cur ≥ 2, which counts the whole last run instead of low + 1 of it.
  • Keeping p in a 32-bit int, so p * 10 overflows when n has ten digits.

How to talk through it

  1. 1Clarify. Is 0 included? Does a number with two 1s count twice? How large can n be?
  2. 2Give the brute force. Count the 1s in every number; say why 10⁹ numbers is too slow.
  3. 3Count one place at a time. The digit at place p is 1 for p numbers in every 10p; split n into high, cur and low.
  4. 4Code the three cases. cur is 0, 1, or 2 and up. Use 64-bit p.
  5. 5Test out loud. Run 0, 5, 11 and 215, and check 0, 1, 4 and 148.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?