Number of Digit One
HardMathdigit counting
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given a non-negative integer n, count how many times the digit 1 is written in total when you write out every integer from 0 through n in decimal.
For example, 11 contributes two ones. Return the total count.
Aim for O(log n) time; iterating over every number is too slow for large n.
Examples
Input: n = 13
Output: 6
The ones appear in 1, 10, 11 (twice), 12, and 13.
Input: n = 0
Output: 0
Only 0 is written, which has no ones.
Constraints
- 0 <= n <= 10^9
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.