Leetcode 1837. Sum of Digits in Base K
1837. Sum of Digits in Base K
Given an integer n
(in base 10) and an integer k
, return the sum of the digits of n
after converting n
from base 10 to base k
.
Input: n = 34, k = 6
Output: 9
Explanation: 34 (base 10) is 54 in base 6. 5 + 4 = 9.
Input: n = 10, k = 10
Output: 1
Explanation: 10 (base 10) is 10 in base 10. 1 + 0 = 1.
1 <= n <= 100
2 <= k <= 10
n < 1
or k < 2
?
1 <= n <= 100
and 2 <= k <= 10
, so we don’t need to handle invalid inputs.k
.n
and k
will always be integers?
To solve the problem, follow these steps:
n
from Base 10 to Base k
:
n
by k
.k
.k
.public class SumOfDigitsInBaseK {
public int sumBase(int n, int k) {
int sum = 0;
while (n > 0) {
sum += n % k;
n /= k;
}
return sum;
}
public static void main(String[] args) {
SumOfDigitsInBaseK solver = new SumOfDigitsInBaseK();
// Test cases
System.out.println(solver.sumBase(34, 6)); // Expected output: 9
System.out.println(solver.sumBase(10, 10)); // Expected output: 1
}
}
n
by a factor of k
. The number of operations required is proportional to (log_k n)
.In summary, the time complexity of this solution is O(log k n), which is efficient given the constraints (1 \le n \le 100) and (2 \le k \le 10).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?