从1-n整数中1出现的次数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_37964071/article/details/81865678

题目:
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

解法一:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int count=0;
        if(n<1) return 0;
        for(int i=1;i<=n;++i)
        {
            int temp=i;
            while(temp)
            {
                if(temp%10==1) 
                    ++count;
                temp/=10;
            }
        }
        return count;
    }
};

解法二:
比解法一效率高很多。

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        if(n<0)
            return 0;
        int high,low,curr,tmp,i = 1;
        high = n;
        int total = 0;
        while(high!=0)
        {
            high = n/(int)pow(10, i);// 获取第i位的高位
            tmp = n%(int)pow(10, i);
            curr = tmp/(int)pow(10, i-1);// 获取第i位
            low = tmp%(int)pow(10, i-1);// 获取第i位的低位
            if(curr==x)
            {
                total+= high*(int)pow(10, i-1)+low+1;
            }
            else if(curr<x)
            {
                total+=high*(int)pow(10, i-1);
            }
            else
            {
                total+=(high+1)*(int)pow(10, i-1);
            }
            i++;
        }
        return total;     
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_37964071/article/details/81865678