Magicsheet logo

Sum of Digits in Base K

Easy
12.5%
Updated 8/1/2025

Asked by 1 Company

Topics

Sum of Digits in Base K

What is this problem about?

In this problem, you are given an integer n in base 10 and a base k. Your task is to convert n into its representation in base k and then find the sum of the digits of that new representation. For example, if n = 34 and k = 6, 34 in base 6 is 54 (because 5*6 + 4 = 34). The sum of the digits 5 and 4 is 9.

Why is this asked in interviews?

This "Easy" level problem is frequently asked at companies like Amazon to test basic mathematical logic and comfort with number bases. It assesses whether a candidate knows how to perform base conversions using the standard "divide and modulo" approach. It's a foundational skill for understanding how data is represented in different formats (binary, octal, hexadecimal) within a computer.

Algorithmic pattern used

The algorithmic pattern is "Base Conversion using Iterative Division." To convert a number n to base k, you repeatedly take the remainder of n divided by k (n % k) to get the current digit, and then update n by dividing it by k (n // k). You keep track of the sum of these remainders until n becomes 0.

Example explanation

Let's convert n = 42 to base k = 4.

  1. 42 % 4 = 2. (Last digit is 2). Update n = 42 // 4 = 10.
  2. 10 % 4 = 2. (Next digit is 2). Update n = 10 // 4 = 2.
  3. 2 % 4 = 2. (Next digit is 2). Update n = 2 // 4 = 0. Digits in base 4 are {2, 2, 2}. Sum of digits: 2 + 2 + 2 = 6.

Common mistakes candidates make

  1. Confusing the result: Trying to actually construct the number as a string or large integer instead of just summing the remainders as they are generated.
  2. Incorrect Loop Condition: Using n > k instead of n > 0, which might miss the final leading digit.
  3. Base 10 habits: Failing to realize that the same logic used for extracting decimal digits (n % 10) applies to any base k.

Interview preparation tip

Be prepared to handle base conversion in any coding interview. It is a very common sub-task in more complex problems. Remember that n % k gives you the digit and n / k moves you to the next position. Practice doing this manually for binary (base 2) and hexadecimal (base 16) to build intuition.

Similar Questions