LeetCode 1837: Sum of Digits in Base K
Problem Description
Explanation
To solve this problem, we can convert the given number n
from base 10 to base k
. Then, we sum the digits of the converted number to get the final result. We can achieve this by repeatedly dividing the number by k
to get the remainder which will be the least significant digit in base k
. We keep track of the sum of digits as we go along.
Algorithm:
- Initialize a variable
sum
to 0. - While
n
is greater than 0:- Calculate the remainder by taking
n % k
. - Add the remainder to
sum
. - Update
n
by doing integer divisionn / k
.
- Calculate the remainder by taking
- Return the
sum
.
Time Complexity
The time complexity of this algorithm is O(logk(n)) where n is the input number and k is the base.
Space Complexity
The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.
Solutions
class Solution {
public int sumBase(int n, int k) {
int sum = 0;
while (n > 0) {
sum += n % k;
n /= k;
}
return sum;
}
}
Loading editor...