#1017
Convert to Base -2
MediumMathMathematical OperationsString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(log n)Space O(n)
The optimal solution leverages the properties of negative base conversion, efficiently calculating the binary representation by adjusting the quotient and remainder in a single loop without unnecessary operations.
⚙️
Algorithm
6 steps- 1Step 1: Initialize an empty string to store the result.
- 2Step 2: While n is not zero, calculate the remainder and quotient using divmod with -2.
- 3Step 3: If the remainder is negative, adjust it by adding 2 and increment the quotient.
- 4Step 4: Prepend the adjusted remainder to the result.
- 5Step 5: Update n to be the quotient and repeat until n is zero.
- 6Step 6: Return the result, ensuring no leading zeros unless the result is '0'.
solution.py11 lines
1def baseNeg2(n):
2 if n == 0:
3 return '0'
4 result = ''
5 while n != 0:
6 n, remainder = divmod(n, -2)
7 if remainder < 0:
8 remainder += 2
9 n += 1
10 result = str(remainder) + result
11 return resultℹ
Complexity note: The time complexity is O(log n) because the number of digits in the base -2 representation grows logarithmically with the value of n. The space complexity is O(n) due to the storage of the result string.
- 1Understanding how negative bases work is crucial.
- 2Adjusting remainders correctly is key to getting the right representation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.