Sum of Digits in Base K - Problem

Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.

After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.

Example: If n = 34 and k = 6, then 34 in base 6 is 54 (since 5×6¹ + 4×6⁰ = 30 + 4 = 34). The sum of digits 5 + 4 = 9.

Input & Output

Example 1 — Basic Conversion
$ Input: n = 34, k = 6
Output: 9
💡 Note: 34 in base 6 is 54 (5×6¹ + 4×6⁰ = 30 + 4 = 34). Sum of digits: 5 + 4 = 9
Example 2 — Base 2 Conversion
$ Input: n = 10, k = 2
Output: 2
💡 Note: 10 in base 2 is 1010 (1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10). Sum: 1 + 0 + 1 + 0 = 2
Example 3 — Edge Case Zero
$ Input: n = 0, k = 10
Output: 0
💡 Note: 0 in any base is 0, so sum of digits is 0

Constraints

  • 1 ≤ n ≤ 100
  • 2 ≤ k ≤ 10

Visualization

Tap to expand
Sum of Digits in Base K INPUT Decimal Number n = 34 Target Base k = 6 Base 10 representation: 3 tens 4 ones 34 = 3×10 + 4×1 Convert to base 6 ALGORITHM STEPS 1 Initialize sum = 0 Track digit sum 2 Get digit: n % k 34 % 6 = 4 (rightmost) 3 Update: n = n / k 34 / 6 = 5 (integer) 4 Repeat until n = 0 5 % 6 = 5, 5 / 6 = 0 Iteration Details: n=34: 34%6=4, sum=4, n=5 n=5: 5%6=5, sum=9, n=0 n=0: STOP 34 in base 6 = "54" FINAL RESULT 34 (base 10) in base 6: 5 4 6^1 6^0 Verify: 5×6 + 4×1 = 34 Sum of Digits: 5 + 4 = 9 (interpreted as base 10) OUTPUT 9 OK - Verified! Key Insight: Use modulo (%) to extract the last digit in base k, then integer divide (/) to remove it. Each digit extracted is already a base-10 value (0 to k-1), so directly add to sum. Time: O(log_k(n)) | Space: O(1) - No need to store the full base-k representation! TutorialsPoint - Sum of Digits in Base K | Direct Mathematical Conversion
Asked in
Google 15 Facebook 12 Amazon 8
12.0K Views
Medium Frequency
~8 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen