|
| 1 | +// Problem Number: 2999 |
| 2 | + |
| 3 | +// Count the Numbers of Powerful Integers. |
| 4 | + |
| 5 | +class Solution { |
| 6 | + private String s; |
| 7 | + private String a, b; |
| 8 | + private int limit; |
| 9 | + private Long[][][] memo; |
| 10 | + |
| 11 | + public long numberOfPowerfulInt(long start, long finish, int limit, String s) { |
| 12 | + this.s = s; |
| 13 | + this.a = String.valueOf(start); |
| 14 | + this.b = String.valueOf(finish); |
| 15 | + this.limit = limit; |
| 16 | + |
| 17 | + // Pad a and s with leading zeros to match the length of b |
| 18 | + a = "0".repeat(b.length() - a.length()) + a; |
| 19 | + s = "0".repeat(b.length() - s.length()) + s; |
| 20 | + |
| 21 | + memo = new Long[b.length()][2][2]; |
| 22 | + |
| 23 | + return count(0, true, true); |
| 24 | + } |
| 25 | + |
| 26 | + private long count(int i, boolean tightA, boolean tightB) { |
| 27 | + if (i + s.length() == b.length()) { |
| 28 | + String aMinSuffix = tightA ? a.substring(b.length() - s.length()) : "0".repeat(s.length()); |
| 29 | + String bMaxSuffix = tightB ? b.substring(b.length() - s.length()) : "9".repeat(s.length()); |
| 30 | + |
| 31 | + long suffix = Long.parseLong(s); |
| 32 | + long aMin = Long.parseLong(aMinSuffix); |
| 33 | + long bMax = Long.parseLong(bMaxSuffix); |
| 34 | + |
| 35 | + return (aMin <= suffix && suffix <= bMax) ? 1 : 0; |
| 36 | + } |
| 37 | + |
| 38 | + int tA = tightA ? 1 : 0; |
| 39 | + int tB = tightB ? 1 : 0; |
| 40 | + if (memo[i][tA][tB] != null) { |
| 41 | + return memo[i][tA][tB]; |
| 42 | + } |
| 43 | + |
| 44 | + long res = 0; |
| 45 | + int minDigit = tightA ? a.charAt(i) - '0' : 0; |
| 46 | + int maxDigit = tightB ? b.charAt(i) - '0' : 9; |
| 47 | + |
| 48 | + for (int d = minDigit; d <= maxDigit; ++d) { |
| 49 | + if (d > limit) continue; |
| 50 | + boolean nextTightA = tightA && (d == minDigit); |
| 51 | + boolean nextTightB = tightB && (d == maxDigit); |
| 52 | + res += count(i + 1, nextTightA, nextTightB); |
| 53 | + } |
| 54 | + |
| 55 | + memo[i][tA][tB] = res; |
| 56 | + return res; |
| 57 | + } |
| 58 | +} |
0 commit comments