Sum of Digits in Base K
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer n (in base 10) and a base k, return _thesum of the digits of _n _after converting _n from base10 to basek.
After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Examples
Example 1
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
Example 2
Input: n = 10, k = 10
Output: 1
Explanation: n is already in base 10. 1 + 0 = 1.
Constraints
1 <= n <= 1002 <= k <= 10
Solution
Method 1 – Repeated Division
Intuition
Convert the number to base k by repeatedly dividing by k and summing the remainders. Each remainder is a digit in the base k representation.
Approach
- Initialize a sum variable to 0.
- While
n > 0, addn % kto the sum and setn = n // k. - Return the sum.
Code
C++
class Solution {
public:
int sumBase(int n, int k) {
int ans = 0;
while (n > 0) {
ans += n % k;
n /= k;
}
return ans;
}
};
Go
func sumBase(n int, k int) int {
ans := 0
for n > 0 {
ans += n % k
n /= k
}
return ans
}
Java
class Solution {
public int sumBase(int n, int k) {
int ans = 0;
while (n > 0) {
ans += n % k;
n /= k;
}
return ans;
}
}
Kotlin
class Solution {
fun sumBase(n: Int, k: Int): Int {
var num = n
var ans = 0
while (num > 0) {
ans += num % k
num /= k
}
return ans
}
}
Python
class Solution:
def sumBase(self, n: int, k: int) -> int:
ans = 0
while n > 0:
ans += n % k
n //= k
return ans
Rust
impl Solution {
pub fn sum_base(mut n: i32, k: i32) -> i32 {
let mut ans = 0;
let mut n = n;
while n > 0 {
ans += n % k;
n /= k;
}
ans
}
}
TypeScript
class Solution {
sumBase(n: number, k: number): number {
let ans = 0;
while (n > 0) {
ans += n % k;
n = Math.floor(n / k);
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(log_k n)— Each division bykreducesn, so the number of steps is proportional to the number of digits in basek. - 🧺 Space complexity:
O(1)— Only a few variables are used.