LeetCode 1067. 范围内的数字计数

文章目录

1. 题目

给定一个在 0 到 9 之间的整数 d,和两个正整数 low 和 high 分别作为上下界。

返回 d 在 low 和 high 之间的整数中出现的次数,包括边界 low 和 high。

示例 1:
输入:d = 1, low = 1, high = 13
输出:6
解释: 
数字 d=11,10,11,12,13 中出现 6 次。
注意 d=1 在数字 11 中出现两次。

示例 2:
输入:d = 3, low = 100, high = 250
输出:35
解释:
数字 d=3103,113,123,130,131,...,238,239,243 出现 35 次。
 
提示:
0 <= d <= 9
1 <= low <= high <= 2×10^8

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/digit-count-in-range
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

剑指Offer - 面试题43. 1~n整数中1出现的次数(找规律+公式)

class Solution {
public:
    int digitsCount(int d, int low, int high) {
        return countDigit(high, d) - countDigit(low-1, d);
    }

    int countDigit(int n, int d) {
        if(n < 0)
            return 0;
        int high, cur, low;
        long sum = 0, i = 1;
        while(n/i)
        {
            high = n/(i*10);
            cur = n/i%10;
            low = n%i; //low = n-n/i*i; //或者
            if(cur < d)
                sum += high*i;
            else if(cur == d)
                sum += high*i+low+1;
            else
                sum += (high+1)*i;
            if(d == 0)//特殊情况,减掉当前以0开头的个数
                sum -= i;
            i *= 10;
        }
        return sum;
    }
};

我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值