5802. 统计好数字的数目
题目出处:https://leetcode-cn.com/problems/count-good-numbers/
思路:
- 对于偶数下标的数字,它有0,2,4,6,8共计5种可能,长度为n的数字字符串有ceil[(1+n]) / 2]个偶数下标。
- 对于奇数下标的数字,它有2,3,5,7共计4种,而长度为n的数字字符串有ceil[n/2]个奇数下标。
- 因此长度为n的数字字符串中,好数字的总数为:
- 5^ceil[(1+n]) / 2] * 4 ^ceil[n/2]
- 用快速幂优化:(参考思路)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;
}
};