#1837
Sum of Digits in Base K
EasyMathMathBase Conversion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(log(n)) | O(log(n)) |
| Space | O(log(n)) | O(1) |
💡
Intuition
Time O(log(n))Space O(1)
The optimal solution is similar to the brute force but focuses on summing the digits directly during the conversion process, avoiding the need to store them in a list.
⚙️
Algorithm
4 steps- 1Step 1: Initialize sum to 0.
- 2Step 2: While n is greater than 0, add n % k to sum.
- 3Step 3: Divide n by k.
- 4Step 4: Return the sum.
solution.py8 lines
1# Full working Python code
2
3def sum_of_digits(n, k):
4 total_sum = 0
5 while n > 0:
6 total_sum += n % k
7 n //= k
8 return total_sumℹ
Complexity note: The time complexity remains O(log(n)) due to the same division process, but the space complexity improves to O(1) since we do not store the digits.
- 1Understanding how to convert between bases is crucial.
- 2Summing digits can often be done in a single pass.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.