1. 程式人生 > >LeetCode233,數字1的個數

LeetCode233,數字1的個數

規律如下:

如果第 i (自右向左,從1開始標號)上的數字是0,則第 i 位可能出現 1 的次數由更高位決定(若沒有高位,則高位為0),等於更高位數乘以當前位數的權重(10i-1)

如果第 i 位上的數字為 1,則第 i 位上出現 1 的次數不僅受更高位影響,還受低位影響(若沒有低位,則低位為0),等於更高位數乘以當前位數的權重 (10i-1) + (低位數 + 1)

如果第 i 位上的數字大於 1,則第 i 位上可能出現 1 的次數僅由更高位決定(若沒有高位,則高位為0),等於(更高位數 + 1)乘以當前位數的權重 (10i-1)

總結:當前位的個數=     {\begin{cases} higher*{10_{}}^{i-1}& \text{ if } i<1 \\ higher*{10_{}}^{i-1}+lower+1 & \text{ if } i= 1\\ (higher+1)*{10_{}}^{i-1}& \text{ if } i>1 \end{cases}}{}

程式碼如下:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        int high=n;
        int cur=0,b=1;
        while(high>0)
        {
            cur=high%10;
            high/=10;
            count+=high*b;
            if(cur==1){
                count+=n%b+1;
            }else if(cur>1){
                count+=b;
            }
            b*=10;
        }
        return count;
    }
};