Skip to content

Commit ace95be

Browse files
authored
Create sum-of-digits-of-string-after-convert.cpp
1 parent e4cd3ed commit ace95be

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n + logn + log(logn) + ...) = O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int getLucky(string s, int k) {
7+
int total = accumulate(cbegin(s), cend(s), 0,
8+
[](const auto& total, const auto& x) {
9+
const auto num = x - 'a' + 1;
10+
return total + num / 10 + num % 10;
11+
});
12+
while (--k && total > 9) {
13+
int new_total = 0;
14+
for (; total; total /= 10) {
15+
new_total += total % 10;
16+
}
17+
total = new_total;
18+
}
19+
return total;
20+
}
21+
};

0 commit comments

Comments
 (0)