Sum of Digits in Base K

easy math base conversion

Problem

You are given a positive integer n written in base 10 and a base k (between 2 and 10). Convert n into its base-k representation, then add up those base-k digits as ordinary decimal numbers and return that sum.

Inputn = 34, k = 6
Output9
34 in base 6 is "54" (5·6 + 4 = 34). Adding the digits gives 5 + 4 = 9.

def sum_base(n, k):
    total = 0
    while n > 0:
        total += n % k
        n //= k
    return total
function sumBase(n, k) {
  let total = 0;
  while (n > 0) {
    total += n % k;
    n = Math.floor(n / k);
  }
  return total;
}
class Solution {
    public int sumBase(int n, int k) {
        int total = 0;
        while (n > 0) {
            total += n % k;
            n /= k;
        }
        return total;
    }
}
int sumBase(int n, int k) {
    int total = 0;
    while (n > 0) {
        total += n % k;
        n /= k;
    }
    return total;
}
Time: O(logk n) Space: O(1)