> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number of Digit One Python Solution with Tests

> Tested Python solution for LeetCode 233 with 35 pytest cases. Generate a practice environment with lcpy.

LeetCode 233, [Hard](/catalog/hard). Topics: [Math](/catalog/topics/math), [Dynamic Programming](/catalog/topics/dynamic-programming), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/number-of-digit-one/description/).

Generate this problem as a practice environment: tested reference solution, 35 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 233   # by problem number
lcpy gen -s number_of_digit_one   # by problem name
```

## Problem

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

### Examples

```
Input: n = 13
Output: 6
```

```
Input: n = 0
Output: 0
```

### Constraints

* 0 \<= n \<= 10\<sup>9\</sup>

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_digit_one/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_digit_one/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log10(n))
    # Space: O(1)
    def count_digit_one(self, n: int) -> int:
        total = 0
        place = 1
        while place <= n:
            high = n // (place * 10)
            cur = (n // place) % 10
            low = n % place
            if cur == 0:
                total += high * place
            elif cur == 1:
                total += high * place + low + 1
            else:
                total += (high + 1) * place
            place *= 10
        return total
```

## Complexity

| Time | Space |
| - | - |
| O(log10(n)) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.