5802. 统计好数字的数目

5802. 统计好数字的数目

题目出处:https://leetcode-cn.com/problems/count-good-numbers/
在这里插入图片描述
在这里插入图片描述
思路

  1. 对于偶数下标的数字,它有0,2,4,6,8共计5种可能,长度为n的数字字符串有ceil[(1+n]) / 2]个偶数下标。
  2. 对于奇数下标的数字,它有2,3,5,7共计4种,而长度为n的数字字符串有ceil[n/2]个奇数下标。
  3. 因此长度为n的数字字符串中,好数字的总数为:
  4. 5^ceil[(1+n]) / 2] * 4 ^ceil[n/2]
  5. 用快速幂优化:(参考思路)https://leetcode-cn.com/problems/powx-n/solution/powx-n-by-leetcode-solution/
class Solution {
private:
    static constexpr int mod = 1000000007;
    
public:
    int countGoodNumbers(long long n) {
        // 快速幂求出 x^y % mod
        auto quickmul = [](int x, long long y) -> int {
            int ret = 1, mul = x;
            while (y > 0) {
                if (y % 2 == 1) {
                    ret = (long long)ret * mul % mod;
                }
                mul = (long long)mul * mul % mod;
                y /= 2;
            }
            return ret;
        };
        
        return (long long)quickmul(5, (n + 1) / 2) * quickmul(4, n / 2) % mod;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值