1. 程式人生 > >ACMer希望你們幫幫他,並把問題更加普遍化,可以很快的求出任意非負整數區間中1出現的次數(從1 到 n 中1出現的次數)。

ACMer希望你們幫幫他,並把問題更加普遍化,可以很快的求出任意非負整數區間中1出現的次數(從1 到 n 中1出現的次數)。

/*

思路:(這裡不僅僅侷限於1,其他數字也是相通的)

找規律,當計算右數第  i  位包含的 X 的個數時:

取第  i  位左邊(高位)的數字,乘以  10 i−1 ,得到基礎值  a 。 取第  i  位數字,計算修正值: 如果大於 X,則結果為  a+ 10 i−1 。 如果小於 X,則結果為  a 。 如果等 X,則取第  i  位右邊(低位)數字,設為  b ,最後結果為  a+b+1 。 相應的程式碼非常簡單,效率也非常高,時間複雜度只有  O( log 10 n) 。 */

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int res = 0,high = n,low,curr,temp,i = 1;
        while(high){
            high = n/(int)pow(10,i);
            temp = n%(int)pow(10,i);
            curr = temp/(int)pow(10,i-1);
            low = temp%(int)pow(10,i-1);
            if(curr<1)
                res += high*(int)pow(10,i-1);
            if(curr>1)
                res += (high+1)*(int)pow(10,i-1);
            if(curr==1)
                res += (high*(int)pow(10,i-1)+low+1);
            i++;
        }
        return res;
    }
};