整数中1出现的次数(从1到n整数中1出现的次数)

时间:2020-03-18 15:34:37   收藏:0   阅读:40

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

题目意思就是 (从1 到 n 中1出现的次数)

这里有两种方法,

一种是暴力计算,时间复杂度为O(nlogn)比较low

// (从1 到 n 中1出现的次数)。
// 暴力解法,双层循环  时间复杂度O(n*logn),效率不高
class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        int times =  0;
        if (n <= 0)
            return times;
        for(int i = 1; i <= n; ++i)
        {
            int temp = i;
            while(temp)
            {
               if (temp % 10 == 1)
               {
                   times++;
               }
               temp /= 10;
            }
        }
        return  times;
    }
};

第二种方法参考牛客讨论区,

https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6?f=discussion

编程之美上面也有

本文采用数学之美上面提出的方法,设定整数点(如1、10、100等等)作为位置点i(对应n的各位、十位、百位等等),分别对每个数位上有多少包含1的点进行分析。

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        // 统计次数
        int count = 0;
        for(int i = 1; i <= n; i *= 10){
            // 计算高位和低位
            int a = n / i, b = n % i;
            count += (a + 8) / 10 * i + (a % 10 == 1) * (b + 1);
        }
        return count;
    }
};

 

原文:https://www.cnblogs.com/xiaokang01/p/12517373.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!