A comprehensive cpp sollution


  • 0
    A
    class Solution {
    public:
        int countDigitOne(int n) {
            if (n <= 0) return 0;
            string s = to_string(n);
            int m = s.size();
    
            vector<int> f(m + 1);
            f[0] = 0; f[1] = 1;
            int ei = 1;
            for(int i = 1; i < m; i++) {
                f[i] = 10 * f[i-1] + ei;
                ei *= 10;
            }
            
            int ans = 0;
            for(int i = 0; i < m; i++) {
                ans += f[m-i-1] * (s[i] - '0');
                if (s[i] == '1' && i < m-1) 
                    ans += stoi(s.substr(i+1)) + 1;
                else if (s[i] != '0')
                    ans += ei;
                ei /= 10;
            }
            
            return ans;
        }
    };
    

    A little tedious but comprehensive.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.