Python 1017.py
class Solution:
def baseNeg2(self, n: int) -> str:
# based on https://oeis.org/A039724
s = ""
while n >= 2 or n < 0:
# integer division, keep remainder
r = n % -2
n = n // -2
# make sure that remainder is always positive
if r < 0:
r += 2
n += 1
s = str(r) + s
return str(n) + s
Difficulty
and has an acceptance rate of about 61% (50k+ 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 Solution class implements a conversion from a signed integer n to its representation in base -2, returning the result as a string. The algorithm follows the standard division-remainder method adapted for a negative radix, ensuring that each digit is non-negative and that the final string correctly reflects the value of the original integer.
Core Logic
The method begins by initializing an empty accumulator s that will hold the digits of the base -2 representation in reverse order.
s = ""
A loop is then entered that continues while the absolute value of n is at least two. The condition while n >= 2 or n < 0: captures both positive numbers that still need further division and negative numbers that have not yet been reduced to a single digit.
Inside the loop the remainder r is obtained using the modulo operator with the negative divisor -2.
r = n % -2
The quotient for the next iteration is computed with integer division by -2.
n = n // -2
Because Python’s modulo operation can yield a negative remainder when the divisor is negative, the code includes a correction step that guarantees r is always 0 or 1. If r is negative, it is increased by 2 and the quotient n is incremented by 1 to preserve the invariant n * (-2) + r equals the original value before the correction.
if r < 0:
r += 2
n += 1
The corrected digit is then prepended to the accumulator string.
s = str(r) + s
When the loop terminates, n holds the most significant digit, which may be 0 or 1. The final result is formed by concatenating this digit with the accumulated suffix.
return str(n) + s
Edge Cases Handled
The algorithm gracefully processes the value 0. In this situation the loop condition evaluates to false immediately, leaving s empty and n equal to 0. The return statement yields "0", which is the correct base -2 representation of zero.
For the input 1, the loop does not execute because n is less than 2 and non-negative. The return statement concatenates "1" with an empty suffix, producing "1".
Negative inputs are fully supported. The loop condition n < 0 ensures that any negative number enters the conversion process. The remainder correction step guarantees that each digit appended to the result is non-negative, thereby handling the sign implicitly through the negative radix rather than an explicit sign character.
Large magnitude numbers, whether positive or negative, are reduced iteratively by division by -2. Each iteration shrinks the absolute value of n, guaranteeing eventual termination.
Performance Optimizations Observed
The implementation relies exclusively on integer arithmetic and string concatenation, avoiding auxiliary data structures such as lists or arrays. By directly constructing the result string through prefixing, the code eliminates the need for a separate reversal step after the loop.
The use of the built-in modulo and floor division operators leverages Python’s optimized low-level arithmetic, ensuring that each iteration performs the minimal amount of work required to extract a digit.
Because the loop condition checks both n >= 2 and n < 0 in a single expression, the algorithm avoids redundant branching and evaluates the continuation criteria efficiently.
Overall, the method achieves the conversion with a tight loop that processes each digit exactly once, maintaining a compact memory footprint and low overhead.
ELI5 - Simplified Explanation
Imagine you have a magical piggy bank that likes to count things in a special way using negative numbers. This code is like a set of secret instructions that turns a regular number into this special secret code.
The machine starts with an empty piece of paper to write down the secret code. It looks at the number you give it and keeps breaking it down into smaller parts over and over again. Each time it breaks the number down, it looks for a little leftover piece. These leftover pieces are like the letters in the secret code.
Sometimes, the leftover piece is a grumpy negative number, so the machine does a quick trick to turn it into a happy, positive number so that everything stays tidy. It keeps track of these leftovers and adds them one by one to the front of the paper. Once the number is small enough that it can no longer be broken down, the machine adds that last piece to the very front of the paper and shows the final secret result.
Code Quality
Complexity Analysis
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 | Java | Go | C# | Rust | TS | ||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 483: Smallest Good Base
- problem 1256: Encode Number
Solved On The Same Day
- problem 524: Longest Word in Dictionary through Deleting
- problem 529: Minesweeper
- problem 842: Split Array into Fibonacci Sequence
- problem 984: String Without AAA or BBB
- problem 1014: Best Sightseeing Pair
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