|
| 1 | +/** |
| 2 | + * 2999. Count the Number of Powerful Integers |
| 3 | + * https://leetcode.com/problems/count-the-number-of-powerful-integers/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given three integers start, finish, and limit. You are also given a 0-indexed string |
| 7 | + * s representing a positive integer. |
| 8 | + * |
| 9 | + * A positive integer x is called powerful if it ends with s (in other words, s is a suffix of x) |
| 10 | + * and each digit in x is at most limit. |
| 11 | + * |
| 12 | + * Return the total number of powerful integers in the range [start..finish]. |
| 13 | + * |
| 14 | + * A string x is a suffix of a string y if and only if x is a substring of y that starts from |
| 15 | + * some index (including 0) in y and extends to the index y.length - 1. For example, 25 is a |
| 16 | + * suffix of 5125 whereas 512 is not. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} start |
| 21 | + * @param {number} finish |
| 22 | + * @param {number} limit |
| 23 | + * @param {string} suffix |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var numberOfPowerfulInt = function(start, finish, limit, suffix) { |
| 27 | + start--; |
| 28 | + const startCount = countValidNums(start, limit, suffix); |
| 29 | + const finishCount = countValidNums(finish, limit, suffix); |
| 30 | + return finishCount - startCount; |
| 31 | + |
| 32 | + function countValidNums(number, maxDigit, suffix) { |
| 33 | + const suffixNum = parseInt(suffix); |
| 34 | + const suffixMod = 10 ** suffix.length; |
| 35 | + const suffixPart = number % suffixMod; |
| 36 | + let baseNum = Math.floor(number / suffixMod); |
| 37 | + if (suffixPart < suffixNum) baseNum--; |
| 38 | + |
| 39 | + if (baseNum <= 0) return baseNum + 1; |
| 40 | + |
| 41 | + const digitStr = baseNum.toString(); |
| 42 | + let count = digitStr.charCodeAt(0) - 48; |
| 43 | + let isExact = 1; |
| 44 | + |
| 45 | + if (count > maxDigit) { |
| 46 | + return (maxDigit + 1) ** digitStr.length; |
| 47 | + } |
| 48 | + |
| 49 | + for (let i = 1; i < digitStr.length; i++) { |
| 50 | + count *= (maxDigit + 1); |
| 51 | + if (isExact) { |
| 52 | + const currentDigit = digitStr.charCodeAt(i) - 48; |
| 53 | + if (currentDigit > maxDigit) { |
| 54 | + isExact = 0; |
| 55 | + count += maxDigit + 1; |
| 56 | + } else { |
| 57 | + count += currentDigit; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return count + isExact; |
| 63 | + } |
| 64 | +}; |
0 commit comments