Sharing my C++ solution


  • 0
    T
    #define Int64 long long int
    
    class Solution {
    public:
        int countDigitOne(int n) {
            Int64 N = n;
            Int64 result=0;
            Int64 m;
            Int64 current, higher, lower;
            Int64 weight=1;
            while(N/weight>0)
            {
                lower = N%weight;
                current = (N/weight)%10;
                higher = N/(weight*10);
                if(current==1)
                    result += higher*weight + lower+1;
                else if(current==0)
                    result += higher*weight;
                else
                    result += (higher+1)*weight;
                    
                weight = weight*10;
            }
            
            return ((int) result);
        }
    };

Log in to reply
 

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