267. Number of Digit One

You are given an integer n. Your task is to calculate and return the total number of times the digit 1 appears in all non-negative integers that are less than or equal to n.

Example 1:

Input: n = 13

Output: 6

Explanation:

The digit 1 appears in the numbers 1, 10, 11, 12, and 13. Notice that the number 11 contributes two 1s. Total count = 1 + 1 + 2 + 1 + 1 = 6.

Example 2:

Input: n = 20

Output: 12

Explanation:

The numbers containing 1 up to 20 are 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, and 19. Total count = 1 (from 1) + 1 (from 10) + 2 (from 11) + 8 (from 12-19) = 12.

Now Your Turn!

Pick the correct output for the given input

Input: n = 0

(Determine the total number of times the digit 1 appears)

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= n <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int countDigitOne(int n) {
}
};
Test Case

Input:

N