Python 1837.py
class Solution:
def sumBase(self, n: int, k: int) -> int:
result = 0
while n > 0:
result += n % k
n //= k
return result
Difficulty
and has an acceptance rate of about 79% (100k+ submissions).
Typical patterns to solve this problem:
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that computes the sum of the digits of a non-negative integer n when expressed in base k. The algorithm repeatedly extracts the least-significant digit in the chosen base, adds it to an accumulator, and reduces the number by discarding the processed digit. The process continues until the entire number has been consumed, at which point the accumulated sum is returned.
Key Steps
The core logic consists of three distinct actions performed inside a loop: digit extraction, accumulation, and reduction of the original number. Each action is represented by a concise line of code that directly maps to the mathematical operation required for base conversion.
Digit Extraction
The expression n % k yields the remainder when n is divided by k. This remainder corresponds to the current least-significant digit in base k.
result += n % k
Accumulation
The extracted digit is added to the variable result, which holds the running total of all digits processed so far. The accumulator is initialized to zero before the loop begins, guaranteeing that the final value reflects only the contributions from the digits of n.
result = 0
Reduction of the Number
After the digit has been accounted for, the statement n //= k performs integer division, effectively shifting the number one digit position to the right in base k. This prepares n for the next iteration of the loop.
n //= k
Loop Control and Termination
The loop condition while n > 0: ensures that the body executes only while there remain digits to process. When n becomes zero, the loop exits and the method returns the accumulated sum.
while n > 0:
# body
return result
Edge Cases
The algorithm gracefully handles the situation where the input number n is zero. In that case, the loop condition n > 0 fails immediately, the body is never executed, and the method returns the initial value of result, which is zero. This matches the mathematical expectation that the sum of the digits of zero in any base is zero.
When the base k is larger than n, the first iteration computes n % k which yields n itself, and the subsequent integer division n //= k reduces n to zero. The loop then terminates after a single iteration, correctly returning n as the sum of its single digit representation in that base.
The code also works correctly for the smallest valid base, which is two. The repeated division by two extracts binary digits, and the accumulator aggregates the count of ones, effectively computing the population count of n.
Performance Optimizations
The implementation achieves efficiency by operating directly on integer arithmetic without allocating auxiliary data structures. Each iteration performs a constant-time modulus and division, both of which are native operations in the underlying runtime. The use of the augmented assignment operators (+= and //=) reduces the overhead of separate variable reads and writes.
By updating n in place, the algorithm avoids the need for a copy of the original value, thereby minimizing memory usage. The loop terminates as soon as n reaches zero, guaranteeing that the number of iterations equals the number of digits in the base-k representation, which is the minimal amount of work required for this computation.
ELI5 - Simplified Explanation
Imagine there is a magical basket that likes numbers. To figure out what goes in the basket, the computer takes a big number and keeps dividing it into smaller piles based on the size of k. Every time it takes a pile out, it looks at how many leftovers are sitting there. Those leftovers get added to a growing pile in the basket. The computer keeps doing this over and over again until all the big numbers are gone, leaving only the final pile of leftovers in the basket.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | JS | Java | C | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2843: Count Symmetric Integers
Solved On The Same Day
- problem 1800: Maximum Ascending Subarray Sum
- problem 1813: Sentence Similarity III
- problem 1824: Minimum Sideway Jumps
- problem 1770: Maximum Score from Performing Multiplication Operations
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality