<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 13
<strong>Output:</strong> 6
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 0
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution {
public:
    int countDigitOne(int n) {
        int ans = 0;
        if(n <= 0) return 0;
        if(n <= 9) return 1;

        unordered_map<int,int> m;
        m[9] = 1;

        for(int i = 9 ; i <= (INT_MAX - 9)/10 ; i = i*10 + 9){
            m[i*10+9] = m[i]*10 + (i+1);
        }

        int new_n = n , div = 1;

        while(new_n/10){
            new_n /= 10;
            div *= 10;
        }

        ans += (n/div)*m[div-1];
        ans += (n/div > 1) ? div : 0;
        ans += (n/div == 1) ? n%div + 1 : 0;
        ans += countDigitOne(n%div);

        return ans;
    }
};
7600