Given an integer n (in decimal base) and an integer k (the base to convert n to), return the sum of the digits of n after converting n from decimal to base k.
Input: n = 34, k = 6
Output: 9
Explanation: 34 in base 6 is 54, which sums to 5 + 4 = 9.
Input: n = 10, k = 10
Output: 1
Explanation: 10 in base 10 is 10, which sums to 1 + 0 = 1.
1 <= n <= 1000002 <= k <= 10n being a power of k?To solve the problem, we need to perform the following steps:
n from decimal to the given base k.k:n by k and record the remainders.k from least significant to most significant.The time complexity for converting a number to a different base is O(log_k n) due to repeated division. Summing the digits will also take O(log_k n). Therefore, the overall time complexity is O(log_k n).
def sum_base_k(n, k):
# Initialize sum of digits to 0
sum_digits = 0
# Convert to base k and sum the digits
while n > 0:
remainder = n % k
sum_digits += remainder
n //= k
return sum_digits
# Test the function with the given examples
print(sum_base_k(34, 6)) # Should print 9
print(sum_base_k(10, 10)) # Should print 1
This code defines a function sum_base_k that converts n from decimal to base k and then sums its digits. It uses a loop to repeatedly divide the number by k, collecting remainders, summing them, and then reducing the number until it is zero.
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?