<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:
    string convert(int n) {
    string ret = "";

    while (n > 0) {
        ret = char(48 + n % 10) + ret;       
        n /= 10;
    }

    if (ret.size() == 0) {
        ret = "0";
    }

    return ret;
}

int countDigitOne(int n) {
    long long ans = 0;
    string s = convert(n);
    long long t[11];

    t[0] = 1;
    for (int i = 1; i <= 10; i++) {
        t[i] = t[i - 1] * 10;
    }

    int cnt = 0;
    for (int i = 0; i < s.size(); i++) {
        int sz = s.size();
        int d = s[i] - 48;
        if (i == s.size() - 1)
            ans += long (cnt * (d + 1) * t[sz - i - 1]);
        else ans += long (cnt * d * t[sz - i - 1]);

        if (sz - i - 1 > 0) 
            ans += t[sz - i - 2] * (d * (sz - i - 1));

        if (s[i] > '1') {
            ans += t[sz - i - 1];
        } else if (s[i] == '1') {
            cnt++;
        }
    }

    if (s[s.size() - 1] == '1') {
        ans++;
    }

    return ans;
}
};
7500