Skip to content

Commit 49e7801

Browse files
authored
Create calculate-digit-sum-of-a-string.cpp
1 parent abf07a1 commit 49e7801

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n + n * (log10(9k)/k) + ... + k)
2+
// = O((n - (log10(9k)/k)*k)/(1-log10(9k)/k))
3+
// = O(n / (1-log10(9k)/k)) = O(n) for k >= 2
4+
// Space: O(n)
5+
6+
// simulation
7+
class Solution {
8+
public:
9+
string digitSum(string s, int k) {
10+
while (size(s) > k) {
11+
string new_s;
12+
for (int i = 0, curr = 0; i < size(s); ++i) {
13+
curr += s[i] - '0';
14+
if (i % k == k - 1 || i == size(s) - 1) {
15+
new_s += to_string(curr);
16+
curr = 0;
17+
}
18+
}
19+
s = move(new_s);
20+
}
21+
return s;
22+
}
23+
};

0 commit comments

Comments
 (0)