just follow the instructions and simulate the problem!
code link to code
class Solution {
public:
string digitSum(string s, int k) {
string nextRound;
while (static_cast<int>(s.size()) > k) {
int i{0};
int sum{0};
for (char c : s) {
sum += c - '0';
++i;
if (i == k) {
nextRound += to_string(sum);
sum = 0;
i = 0;
}
}
if (i > 0) {
nextRound += to_string(sum);
}
swap(s, nextRound);
nextRound.clear();
}
return s;
}
};complexity link to complexity
- Time:
O(n)wheren = s.size()- Space:
O(n)
time taken link to time taken
- 7 minutes and 34 seconds