56. 从1到n整数中1出现的次数

 

 https://www.cnblogs.com/wangkundentisy/p/8946858.html

结论:

对于数字n,计算它的第i(i从1开始,从右边开始计数)位数上包含的数字1的个数:

假设第i位上的数字为x的话,则

1.如果x > 1的话,则第i位数上包含的1的数目为:(高位数字 + 1)* 10 ^ (i-1)  (其中高位数字是从i+1位一直到最高位数构成的数字)

2.如果x < 1的话,则第i位数上包含的1的数目为:(高位数字 )* 10 ^ (i-1)

3.如果x == 1的话,则第i位数上包含1的数目为:(高位数字) * 10 ^ (i-1) +(低位数字+1)   (其中低位数字时从第i - 1位数一直到第1位数构成的数字)

class Solution {
public:
    int numberOf1Between1AndN_Solution(int n) {
        if( n < 0)
        return 0;
        int i = 1;
        int high = n;
        int cnt = 0;
        while(high != 0)
        {
            high = n / pow(10 ,i);//high表示当前位的高位
            int temp = n / pow(10, i - 1);
            int cur = temp % 10;//cur表示第i位上的值,从1开始计算
            int low = n  - temp * pow(10, i - 1);//low表示当前位的低位
            if(cur < 1)
            {
                cnt += high * pow(10, i - 1);
            }
            else if(cur > 1)
            {
                cnt += (high + 1) * pow(10 ,i - 1);
     
            }
            else
            {
     
                cnt += high * pow(10, i - 1);
                cnt += (low + 1);
     
            }
            i++;
        }
        return cnt;
            
        }
};

 

AcWing 56. 从1到n整数中1出现的次数

 

posted @ 2020-02-17 16:15  靖愁  阅读(203)  评论(0编辑  收藏  举报