1837. Sum of Digits in Base K


Problem Description

The problem asks for converting an integer n from base 10 to a given base k and then to find the sum of the digits of the new number in base k. It's important to note that after conversion, each digit of the base k number should be treated as an individual base 10 number. Finally, the sum of these base 10 values of the digits should be returned also in base 10.

To illustrate this with an example, if n is 34 and k is 6, the base 6 representation of 34 would be 54 (5*6^1 + 4*6^0). The sum needed would be the sum of the digits 5 and 4 in base 10, which equals 9.

Intuition

The solution follows a simple mathematical approach, consisting of repeatedly dividing the given number n by the base k and taking the remainder as the next base k digit. This is a common mathematical strategy to convert numbers from base 10 to another base.

The core intuition is that in each division step, n % k gives us the digit in the ones place of the base k number, and n // k reduces n to remove that digit. We keep track of the sum of these digits as we find them by adding n % k to ans at each step, which is initialized as 0. This process continues until n is reduced to 0, at which point we've looked at each digit of the number in base k, and ans holds their sum.

By treating each digit as a base 10 number immediately upon discovery, we avoid the need to first fully convert n to base k as a separate step before summing the digits. We're effectively converting and summing in one pass, which is efficient and straightforward.

Learn more about Math patterns.

Solution Approach

The implementation of the solution makes use of a simple loop and arithmetic operations to achieve the conversion and digit summation. No complex data structures or patterns are necessary, which makes the algorithm easy to understand and efficient in terms of both time and space complexity.

Here's an explanation of the steps taken in the given Python code:

  1. We initialize ans to 0, which will be used to keep track of the cumulative sum of the base k digits.

  2. We start a while loop that will run as long as n is not 0. Within each iteration of the loop, we are dealing with two tasks: converting to base k and summing up the digits.

  3. The expression n % k is evaluated, which will give us the least significant digit in the base k representation of our number. For example, if n is 34 and k is 6, in the first iteration, we will get 4 because 34 % 6 equals 4.

  4. We add this digit to ans, effectively summing the digits as we generate them in the base k representation.

  5. Next, we need to update n for the next iteration. We do this by floor-dividing n by k using the expression n //= k. Floor division (//) gives us the quotient when n is divided by k, which effectively shifts our base k number to the right, discarding the digit we just added to ans.

  6. The loop continues until n is reduced to 0, meaning we have processed all digits in the base k number.

After the loop exits, the final result, which is the sum of the digits in base k, is stored in ans. This value is then returned.

This approach is grounded in arithmetic and the properties of number base conversion. It is efficient, as it does not require any additional memory beyond a few integer variables, and all operations are basic arithmetic which can be performed in constant time relative to the number of digits in the base k representation.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's take n = 29 and k = 7 as a small example to illustrate the solution approach. We are tasked with converting the integer n from base 10 to base k and then finding the sum of the digits of the resulting number when each digit is considered as a separate base 10 number.

  1. We start by initializing ans to 0. This will keep track of the cumulative sum of the base k digits.

  2. Since n is not 0, we enter the while loop.

  3. During the first iteration, we calculate n % k. For our example, 29 % 7 is 1. The number 1 is the least significant digit in the base 7 representation of the number 29.

  4. We then add this digit to ans, so ans is now 1.

  5. We prepare for the next iteration by updating n with n // k. For our example, 29 // 7 is 4. So now n becomes 4.

  6. The while loop executes again because n is not 0.

  7. During the second iteration, n % k gives 4 % 7, which is 4. This is the next digit in the base 7 representation, which is also the most significant digit since n is now less than k.

  8. We add the 4 to ans, resulting in ans being 1 + 4 or 5.

  9. We update n with n // k again. This time, 4 // 7 is 0, since 4 is less than 7.

  10. The while loop terminates because n is now 0.

The final result stored in ans is 5, which is the sum of the digits 4 and 1 of the number 29 when converted to base 7. This sum 5 is returned as the result.

Solution Implementation

1class Solution:
2    def sumBase(self, n: int, k: int) -> int:
3        """
4        Calculate the sum of digits of a number 'n' represented in base 'k'.
5
6        Parameters:
7        n (int): The integer number to be converted.
8        k (int): The base to which the number 'n' is to be converted.
9      
10        Returns:
11        int: The sum of the digits of the number 'n' in base 'k'.
12        """
13
14        # Initialize the variable to store the sum of digits
15        digit_sum = 0
16      
17        # Continue looping until the number becomes 0
18        while n > 0:
19            # Add the last digit of 'n' in base 'k' to 'digit_sum'
20            digit_sum += n % k
21          
22            # Remove the last digit by dividing 'n' by the base 'k'
23            n //= k
24
25        # Return the sum of the digits
26        return digit_sum
27
1class Solution {
2    // Method to calculate the sum of digits of 'n' when represented in base 'k'
3    public int sumBase(int n, int k) {
4        // Initialize the result variable to store the sum of digits
5        int result = 0;
6      
7        // Continue the process until 'n' becomes 0
8        while (n != 0) {
9            // Add the last digit of 'n' in base 'k' to the result
10            result += n % k;  // 'n % k' gives the last digit when 'n' is represented in base 'k'
11          
12            // Divide 'n' by 'k' to remove the last digit, reducing 'n'
13            n /= k;  // 'n' is now equal to 'n' without its last digit in base 'k'
14        }
15      
16        // Return the sum of digits of 'n' in base 'k'
17        return result;
18    }
19}
20
1class Solution {
2public:
3    // Function to calculate the sum of digits of the number 'n' when it is represented in base 'k'.
4    int sumBase(int n, int k) {
5        int sum = 0; // Initialize the sum of digits to 0
6        while (n > 0) { // Continue until the number becomes 0
7            sum += n % k; // Add the last digit of 'n' in base 'k' to sum
8            n /= k; // Divide 'n' by 'k' to remove the last digit
9        }
10        return sum; // Return the calculated sum of digits in base 'k'
11    }
12};
13
1// This function calculates the sum of the digits of a number n when represented in base k.
2function sumBase(n: number, k: number): number {
3    let sum = 0; // Initialize sum to store the sum of the digits in base k.
4
5    // Loop continues until n is reduced to 0.
6    while (n) {
7        sum += n % k; // Add the remainder of n divided by k to sum, this is the rightmost digit in base k.
8        n = Math.floor(n / k); // Update n to be the quotient of n divided by k, removing the rightmost digit in base k.
9    }
10
11    // The function returns the sum of digits of n in base k.
12    return sum;
13}
14

Time and Space Complexity

The time complexity of the provided code is O(log_k(n)). This result is due to the fact that in each iteration, the number n is divided by the base k, which decreases n exponentially until it reaches 0. The number of iterations required is proportional to the number of digits of n in base k, which is why the logarithm comes into play.

As for the space complexity, it is O(1) which means it is constant. The reason for this is that the variables ans and n are being reused and updated with each iteration, and no additional space is required that scales with the input size.

Learn more about how to find time and space complexity quickly using problem constraints.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Consider the classic dynamic programming of fibonacci numbers, what is the recurrence relation?


Recommended Readings

Want a Structured Path to Master System Design Too? Donā€™t Miss This!


Load More