|
| 1 | +/** |
| 2 | + * 1922. Count Good Numbers |
| 3 | + * https://leetcode.com/problems/count-good-numbers/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A digit string is good if the digits (0-indexed) at even indices are even and the digits |
| 7 | + * at odd indices are prime (2, 3, 5, or 7). |
| 8 | + * |
| 9 | + * For example, "2582" is good because the digits (2 and 8) at even positions are even and |
| 10 | + * the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 |
| 11 | + * is at an even index but is not even. |
| 12 | + * |
| 13 | + * Given an integer n, return the total number of good digit strings of length n. Since the |
| 14 | + * answer may be large, return it modulo 109 + 7. |
| 15 | + * |
| 16 | + * A digit string is a string consisting of digits 0 through 9 that may contain leading zeros. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} n |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var countGoodNumbers = function(n) { |
| 24 | + const MOD = 1e9 + 7; |
| 25 | + const evenCount = 5; |
| 26 | + const primeCount = 4; |
| 27 | + const evenPositions = Math.ceil(n / 2); |
| 28 | + const oddPositions = Math.floor(n / 2); |
| 29 | + const evenResult = power(evenCount, evenPositions); |
| 30 | + const oddResult = power(primeCount, oddPositions); |
| 31 | + |
| 32 | + return Number(BigInt(evenResult) * BigInt(oddResult) % BigInt(MOD)); |
| 33 | + |
| 34 | + function power(base, exponent) { |
| 35 | + if (exponent === 0) return 1; |
| 36 | + let half = power(base, Math.floor(exponent / 2)); |
| 37 | + half = BigInt(half) * BigInt(half) % BigInt(MOD); |
| 38 | + if (exponent % 2) half = half * BigInt(base) % BigInt(MOD); |
| 39 | + return Number(half); |
| 40 | + } |
| 41 | +}; |
0 commit comments