1837. Sum of Digits in Base K
Problem Description
You are given two integers: n
(a number in base 10) and k
(a target base). Your task is to convert the number n
from base 10 to base k
, then calculate the sum of all the digits in the base k
representation.
For example, if n = 34
and k = 6
:
- First convert 34 (base 10) to base 6:
34 = 5×6¹ + 4×6⁰ = 54
in base 6 - The digits in base 6 representation are 5 and 4
- Sum these digits:
5 + 4 = 9
- Return 9 (in base 10)
The key steps are:
- Convert the number
n
from decimal (base 10) to basek
- Take each digit from the base
k
representation - Add up all these digits treating them as base 10 numbers
- Return the sum in base 10
The solution uses the standard base conversion algorithm: repeatedly divide n
by k
and collect the remainders. Each remainder represents a digit in the base k
representation. By summing these remainders directly, we get the sum of the digits without explicitly constructing the base k
number.
Intuition
When converting a number from base 10 to another base k
, we repeatedly divide by k
and collect the remainders. These remainders are actually the digits of the number in base k
, reading from right to left.
For instance, to convert 34 to base 6:
34 ÷ 6 = 5
remainder4
(rightmost digit)5 ÷ 6 = 0
remainder5
(next digit)- So 34 in base 6 is
54
The key insight is that we don't actually need to construct the base k
number. Since we want the sum of the digits, and each remainder we get during the conversion process IS one of those digits, we can simply add up the remainders as we calculate them.
The algorithm naturally emerges:
- Take
n % k
- this gives us the rightmost digit in basek
- Add this digit to our running sum
- Update
n
ton // k
to remove the rightmost digit we just processed - Repeat until
n
becomes 0
This way, we're simultaneously converting to base k
AND summing the digits, without ever needing to store the actual base k
representation. Each remainder operation n % k
gives us exactly one digit of the base k
number, and we accumulate these digits directly into our answer.
Learn more about Math patterns.
Solution Approach
The solution implements the standard base conversion algorithm with direct digit summation. Here's how the code works:
def sumBase(self, n: int, k: int) -> int:
ans = 0
while n:
ans += n % k
n //= k
return ans
Step-by-step walkthrough:
-
Initialize the sum: We start with
ans = 0
to accumulate the sum of digits. -
Extract digits using modulo: The operation
n % k
gives us the remainder whenn
is divided byk
. This remainder is exactly the rightmost digit ofn
when expressed in basek
. -
Accumulate the digit: We add this digit to our running sum with
ans += n % k
. -
Remove the processed digit: The integer division
n //= k
removes the rightmost digit fromn
in basek
representation. This is equivalent to shifting all digits one position to the right. -
Repeat until exhausted: The
while n:
loop continues as long asn
is non-zero. Whenn
becomes 0, we've processed all digits.
Example trace with n = 34
, k = 6
:
- Iteration 1:
ans = 0 + (34 % 6) = 0 + 4 = 4
, thenn = 34 // 6 = 5
- Iteration 2:
ans = 4 + (5 % 6) = 4 + 5 = 9
, thenn = 5 // 6 = 0
- Loop ends, return
ans = 9
The algorithm has a time complexity of O(log_k(n))
since we divide n
by k
in each iteration, and space complexity of O(1)
as we only use a constant amount of extra space.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's trace through the algorithm with n = 23
and k = 5
:
Goal: Convert 23 to base 5, then sum its digits.
Initial state: n = 23
, ans = 0
Iteration 1:
- Calculate remainder:
23 % 5 = 3
(this is the rightmost digit in base 5) - Add to sum:
ans = 0 + 3 = 3
- Remove processed digit:
n = 23 // 5 = 4
Iteration 2:
- Calculate remainder:
4 % 5 = 4
(this is the next digit in base 5) - Add to sum:
ans = 3 + 4 = 7
- Remove processed digit:
n = 4 // 5 = 0
Iteration 3:
- Since
n = 0
, the loop terminates
Result: The function returns ans = 7
Verification:
- 23 in base 5 is indeed
43
(since 4×5¹ + 3×5⁰ = 20 + 3 = 23) - Sum of digits: 4 + 3 = 7 ✓
The key insight is that each modulo operation extracts exactly one digit from the base-k representation, and we accumulate these digits directly without ever constructing the full base-k number.
Solution Implementation
1class Solution:
2 def sumBase(self, n: int, k: int) -> int:
3 """
4 Calculate the sum of digits of n when represented in base k.
5
6 Args:
7 n: A positive integer to be converted to base k
8 k: The target base (2 <= k <= 10)
9
10 Returns:
11 The sum of all digits in the base-k representation of n
12 """
13 digit_sum = 0
14
15 # Convert n to base k and sum up the digits
16 while n > 0:
17 # Get the rightmost digit in base k (remainder when divided by k)
18 digit_sum += n % k
19
20 # Remove the rightmost digit (integer division by k)
21 n //= k
22
23 return digit_sum
24
1class Solution {
2 /**
3 * Calculates the sum of digits when integer n is represented in base k.
4 *
5 * @param n The non-negative integer to be converted
6 * @param k The base for conversion (k >= 2)
7 * @return The sum of all digits in base k representation
8 */
9 public int sumBase(int n, int k) {
10 int digitSum = 0;
11
12 // Convert n to base k and sum up the digits
13 while (n != 0) {
14 // Extract the rightmost digit in base k
15 digitSum += n % k;
16
17 // Remove the rightmost digit by dividing by base k
18 n /= k;
19 }
20
21 return digitSum;
22 }
23}
24
1class Solution {
2public:
3 /**
4 * Calculate the sum of digits when number n is represented in base k
5 * @param n: The decimal number to be converted
6 * @param k: The target base (2 <= k <= 10)
7 * @return: The sum of all digits in base k representation
8 */
9 int sumBase(int n, int k) {
10 int digitSum = 0;
11
12 // Convert n to base k and sum up each digit
13 while (n > 0) {
14 // Extract the rightmost digit in base k
15 digitSum += n % k;
16
17 // Remove the rightmost digit by integer division
18 n /= k;
19 }
20
21 return digitSum;
22 }
23};
24
1/**
2 * Calculates the sum of digits of a number n when converted to base k
3 * @param n - The decimal number to convert
4 * @param k - The target base (2 <= k <= 10)
5 * @returns The sum of all digits in base k representation
6 */
7function sumBase(n: number, k: number): number {
8 // Initialize sum accumulator
9 let digitSum: number = 0;
10
11 // Convert n to base k and sum the digits
12 while (n > 0) {
13 // Get the rightmost digit in base k (remainder when divided by k)
14 digitSum += n % k;
15
16 // Remove the rightmost digit by integer division
17 n = Math.floor(n / k);
18 }
19
20 return digitSum;
21}
22
Time and Space Complexity
Time Complexity: O(log_k(n))
The algorithm converts a number n
from base 10 to base k
by repeatedly dividing n
by k
and extracting the remainder. In each iteration of the while loop:
- We perform a modulo operation (
n % k
) to get the current digit in basek
- We perform integer division (
n //= k
) to remove the processed digit
The number of iterations equals the number of digits in the base-k
representation of n
. Since a number n
has approximately log_k(n) + 1
digits when represented in base k
, the loop executes O(log_k(n))
times. Each operation inside the loop (modulo, division, addition) takes O(1)
time, resulting in an overall time complexity of O(log_k(n))
.
Space Complexity: O(1)
The algorithm uses only a constant amount of extra space:
- Variable
ans
to store the running sum - The input variable
n
is modified in place
No additional data structures (arrays, lists, recursion stack) are used that grow with the input size. Therefore, the space complexity is O(1)
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Attempting to Build the String Representation First
A common mistake is trying to construct the complete base-k number as a string or list before summing the digits:
Inefficient approach:
def sumBase(self, n: int, k: int) -> int:
# Building string representation first
base_k_str = ""
while n > 0:
base_k_str = str(n % k) + base_k_str
n //= k
# Then summing the digits
return sum(int(digit) for digit in base_k_str)
Why it's problematic:
- Uses extra O(log_k(n)) space for string storage
- Requires additional iteration through the string
- More operations: string concatenation, type conversions
Better solution: Sum the digits directly during conversion (as shown in the original solution).
2. Forgetting to Handle n = 0 Edge Case
While the given solution handles n = 0
correctly (returns 0), some implementations might have issues:
Problematic variation:
def sumBase(self, n: int, k: int) -> int:
if n == 0: # Unnecessary special case
return 0
ans = 0
while n > 0: # Using n > 0 instead of just n
ans += n % k
n //= k
return ans
Solution: The original while n:
elegantly handles all cases including n = 0.
3. Integer Overflow in Other Languages
In languages like C++ or Java, you might encounter integer overflow for large values:
C++ pitfall:
int sumBase(int n, int k) {
int ans = 0;
while (n) {
ans += n % k; // Could overflow for large sums
n /= k;
}
return ans;
}
Solution for C++/Java: Use appropriate data types (long long in C++, long in Java) or verify constraints.
4. Incorrect Order of Operations
Some might mistakenly update n
before extracting the digit:
Wrong approach:
def sumBase(self, n: int, k: int) -> int:
ans = 0
while n:
n //= k # Wrong: dividing before taking remainder
ans += n % k # This gets the wrong digit
return ans
Solution: Always extract the digit (n % k
) before updating n (n //= k
).
What is the best way of checking if an element exists in an unsorted array once in terms of time complexity? Select the best that applies.
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!