[LeetCode] Sum of Digits in Base K

1837. Sum of Digits in Base K

Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.

After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int sumBase(int n, int k) {
vector<int> base;
while(n) {
base.push_back(n%k);
n /= k;
}
int res = 0;
for(auto& num : base) {
res += num;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/25/PS/LeetCode/sum-of-digits-in-base-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.