/**
* Problem: LeetCode 2243 - Calculate Digit Sum of a String
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public String digitSum(String s, int k) {
while (s.length() > k) {
StringBuilder next = new StringBuilder();
for (int i = 0; i < s.length(); i += k) {
int sum = 0;
int end = Math.min(i + k, s.length());
for (int j = i; j < end; j++) {
sum += s.charAt(j) - '0';
}
next.append(sum);
}
s = next.toString();
}
return s;
}
}
"""
Problem: LeetCode 2243 - Calculate Digit Sum of a String
Difficulty: Easy
Language: Python 3
Author: CodeByTushu
"""
class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
next_chunks = []
for i in range(0, len(s), k):
chunk = s[i:i + k]
digit_sum = sum(int(ch) for ch in chunk)
next_chunks.append(str(digit_sum))
s = "".join(next_chunks)
return s
/**
* Problem: LeetCode 2243 - Calculate Digit Sum of a String
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <algorithm>
class Solution {
public:
std::string digitSum(std::string s, int k) {
while (static_cast<int>(s.length()) > k) {
std::string next = "";
int n = static_cast<int>(s.length());
for (int i = 0; i < n; i += k) {
int sum = 0;
int end = std::min(i + k, n);
for (int j = i; j < end; ++j) {
sum += s[j] - '0';
}
next += std::to_string(sum);
}
s = next;
}
return s;
}
};
/**
* Problem: LeetCode 2243 - Calculate Digit Sum of a String
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var digitSum = function(s, k) {
while (s.length > k) {
let next = "";
for (let i = 0; i < s.length; i += k) {
let sum = 0;
const end = Math.min(i + k, s.length);
for (let j = i; j < end; j++) {
sum += Number(s[j]);
}
next += sum;
}
s = next;
}
return s;
};
TIME COMPLEXITY
O(N)
SPACE COMPLEXITY
O(N)
TOPICS
Array
Data Structure
Simulation
String
String Matching