Share my c++ solution


  • 0
    Z
    class Solution {
    public:
        int PowOf10(int n) {
            int t = 1;
            int ans = 0;
            for (int i = 0; i<n; i++) {
                ans = ans * 10 + t;
                t *= 10;
            }
            return ans;
        }
        int countDigitOne(int n) {
            if (n < 10) return n>=1?1:0;
            int t = n, i = 0, p = 1;
            while (t >= 10) {
                t /= 10;
                i++;
                p *= 10;
            }
            int a = n/p*PowOf10(i);
            int b = n/p==1?n%p+1:p;
            int c = countDigitOne(n%p);
            return a+b+c;
    
        }
    };

Log in to reply
 

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