-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculate_digit_sum_of_string.js
50 lines (46 loc) · 1.23 KB
/
calculate_digit_sum_of_string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// https://leetcode.com/problems/calculate-digit-sum-of-a-string/description/
// 2243. Calculate Digit Sum of a String
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var digitSum = function(s, k) {
while (s.length > k) {
let new_s = ''; // each round accumalate new string new_s
for (let i = 0; i < s.length; i += k) {
let sub = s.slice(i, i + k),
sum = 0;
for (const c of sub) sum += c - '0'; // sum of each digits
new_s += sum; // rebuild new string with sum
}
s = new_s; // update new string to s
}
return s;
};
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var digitSumII = function(s, k) {
while (s.length > k) {
let newString = "";
for (let i = 0; i < s.length; i += k)
newString += s.substring(i, i + k).split("").reduce((acc, val) => acc + (+val), 0);
s = newString;
}
return s;
};
console.log(digitSum("11111222229", 3));
// Output: "132"
console.log(digitSum("11111222223", 3));
// Output: "135"
console.log(digitSum("00000000", 3));
// Output: "000"
console.log(digitSumII("11111222229", 3));
// Output: "132"
console.log(digitSumII("11111222223", 3));
// Output: "135"
console.log(digitSumII("00000000", 3));
// Output: "000"