剑指Offer:整数中 1 出现的次数

剑指Offer:整数中 1 出现的次数

题目

题目描述

分析

就是总结数学规律。
分解让复杂问题变简单。
对于任意给定的 N,分别分析从 1 到 N 在不同位置(个位、十位、百位……) 上累计出现的 1 的个数。 可以发现:
在这里插入图片描述

代码

先按上面的想法写了一个智障版本,然后发现根本不需要用到字符串。

智障版本:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
        if (n == 0) return 0;
        int result = 0;
        string nstr = to_string(n);
        if (nstr[0] == '1') result += (StringToInt(nstr.substr(1)) + 1);
        else result += getMulti(nstr.size() - 1);
        for (size_t i = 1; i < nstr.size(); ++i) {
            int high = StringToInt(nstr.substr(0, i));
            int mul = getMulti(nstr.size() - i - 1);
            if (nstr[i] == '0') 
                result += (high * mul);
            else if (nstr[i] == '1') {
                int low = StringToInt(nstr.substr(i + 1));
                result += (high * mul + low + 1);
            }
            else
                result += ((high + 1) * mul);
        }
        return result;
    }
    inline int StringToInt(const string& str)
    {
        return str.empty() ? 0 : stoi(str);
    }
    inline int getMulti(size_t t)
    {
        int result = 1;
        while (t--) result *= 10;
        return result;
    }
};

非智障版本
进一步归纳发现高位其实也可以总结到低位里,得到下图。
在这里插入图片描述
代码如下:

class Solution {
public:
    int NumberOf1Between1AndN_Solution(int n)
    {
    	// 我只是一个可爱的小楼野马,但是 我太难了。其实也可以不用判断 n == 0
        if (n == 0) return 0;
        int result = 0, mul = 1, low = 0, high = n, d;
        while (high > 0) {
            d = high % 10;
            low = n - high * mul;
            high /= 10;
            switch(d) {
                case 0:
                    result += high * mul;
                    break;
                case 1:
                    result += high * mul + low + 1;
                    break;
                default:
                    result += (high + 1) * mul;
            }
            mul *= 10;
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值