Leetcode 2243. Calculate Digit Sum of a String
You are given a string s
consisting of digits and an integer k
. You need to transform the string into a new string according to the following process:
s
into groups of size k
.k
, this is fine and you should proceed with summing the digits in the current groups to form a new string.s
with the sum of the digits in the respective group.k
.Return the final string as the output.
s
?
s
is already of length less than or equal to k
?
s
without any changes.s
?
s
consists of digits only.#include <iostream>
#include <string>
#include <numeric>
#include <algorithm>
// Function to calculate the digit sum of a string
std::string digitSum(std::string s, int k) {
while (s.length() > k) {
std::string new_s = "";
for (size_t i = 0; i < s.length(); i += k) {
int sum = 0;
for (size_t j = i; j < i + k && j < s.length(); ++j) {
sum += s[j] - '0'; // Convert char digit to integer and add to sum
}
new_s += std::to_string(sum); // Append the sum to the new string
}
s = new_s;
}
return s;
}
// Testing the function
int main() {
std::string s = "1111122222";
int k = 3;
std::string result = digitSum(s, k);
std::cout << "Result: " << result << std::endl;
return 0;
}
k
.k
.k
to compute the sum for each segment.k
, return the string as is.The time complexity of this approach is O(n*log(n/k)):
k
.Here, n
is the length of the initial string s
.
This ensures that the solution should work efficiently even for moderately large strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?