Skip to content

Commit c13bfe8

Browse files
committed
Add solution #3463
1 parent 4bd9636 commit c13bfe8

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,7 @@
844844
3452|[Sum of Good Numbers](./3452-sum-of-good-numbers.js)|Easy|
845845
3461|[Check If Digits Are Equal in String After Operations I](./3461-check-if-digits-are-equal-in-string-after-operations-i.js)|Easy|
846846
3462|[Maximum Sum With at Most K Elements](./3462-maximum-sum-with-at-most-k-elements.js)|Medium|
847+
3463|[Check If Digits Are Equal in String After Operations II](./3463-check-if-digits-are-equal-in-string-after-operations-ii.js)|Hard|
847848

848849
## License
849850

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* 3463. Check If Digits Are Equal in String After Operations II
3+
* https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-ii/
4+
* Difficulty: Hard
5+
*
6+
* You are given a string s consisting of digits. Perform the following operation repeatedly until
7+
* the string has exactly two digits:
8+
* - For each pair of consecutive digits in s, starting from the first digit, calculate a new digit
9+
* as the sum of the two digits modulo 10.
10+
* - Replace s with the sequence of newly calculated digits, maintaining the order in which they
11+
* are computed.
12+
*
13+
* Return true if the final two digits in s are the same; otherwise, return false.
14+
*/
15+
16+
/**
17+
* @param {string} s
18+
* @return {boolean}
19+
*/
20+
var hasSameDigits = function(s) {
21+
const n = s.length;
22+
const binomialMod2 = (k, n) => (k & n) === k ? 1 : 0;
23+
const binomialMod5 = (k, n) => {
24+
if (k > n) return 0;
25+
let result = 1;
26+
const pascalMod5 = [
27+
[1, 0, 0, 0, 0],
28+
[1, 1, 0, 0, 0],
29+
[1, 2, 1, 0, 0],
30+
[1, 3, 3, 1, 0],
31+
[1, 4, 1, 4, 1]
32+
];
33+
34+
while (k > 0 || n > 0) {
35+
const ki = k % 5;
36+
const ni = n % 5;
37+
if (ki > ni) return 0;
38+
result = (result * pascalMod5[ni][ki]) % 5;
39+
k = Math.floor(k / 5);
40+
n = Math.floor(n / 5);
41+
}
42+
return result;
43+
};
44+
45+
const binomialMod10 = (k, n) => {
46+
const mod2 = binomialMod2(k, n);
47+
const mod5 = binomialMod5(k, n);
48+
for (let i = 0; i < 10; i++) {
49+
if (i % 2 === mod2 && i % 5 === mod5) return i;
50+
}
51+
return 0;
52+
};
53+
54+
let sum1 = 0;
55+
let sum2 = 0;
56+
for (let i = 0; i <= n - 2; i++) {
57+
const coeff = binomialMod10(i, n - 2);
58+
sum1 = (sum1 + coeff * +s[i]) % 10;
59+
sum2 = (sum2 + coeff * +s[i + 1]) % 10;
60+
}
61+
62+
return sum1 === sum2;
63+
};

0 commit comments

Comments
 (0)