Base -2 Chronicles: Turning Numbers into Binary Rebels 🤖
Intuition
The intuition behind base -2 conversion is to represent a number using powers of -2, where coefficients are either 0 or 1. By repeatedly dividing the
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- The intuition behind base -2 conversion is to represent a number using powers of -2, where coefficients are either 0 or 1. By repeatedly dividing the number by -2 and adjusting negative remainders, we build the representation digit by digit. This ensures the result satisfies the unique properties of the base -2 system.
# Approach
<!-- Describe your approach to solving the problem. -->
1. **Base -2 Representation:** Convert a decimal number `n` into its base -2 equivalent using repeated division by `-2`.
2. **Division and Remainder:** 
- Calculate the remainder (`rem = n % -2`) and quotient (`n = n / -2`).
- If the remainder is negative, adjust it by adding 2 and incrementing the quotient (`n += 1`) to maintain a valid base -2 representation.
3. **Build Result:** Append each adjusted remainder (as a string) to the beginning of the result string (`ans`).
4. **Edge Case:** If n is 0, directly return `"0"` as the result.
---
# Code Explanation:
1. **Initialize Variables:** 
- `ans = ""` for storing the base -2 result.
2. **Edge Case:**
- If `n == 0`, return `"0"`.
3. **While Loop:**
- Calculate `rem = n % -2`.
- Update `n = n / -2`.
- If `rem < 0`, adjust it (`rem += 2`) and increment `n`.
- Append `rem` to the front of `ans`.
4. **Return Result:**
- Return `ans` after the loop ends.
---
# Complexity
- **Time complexity:** $$O(log2|n|)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
 
- **Space complexity:** $$O(log2|n|)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

---
# Code
```cpp []
class Solution {
public:
    string baseNeg2(int n) {
        string ans = "";
        int t = 0, sum = 0;

        if(n==0)
            return "0";
            
        while (n != 0) 
        {
            int rem = n % (-2);
            n = n / (-2);

            if (rem < 0) 
            {
                n = n + 1;
                rem = rem + 2;
            }

            ans = to_string(rem) + ans;
        }

        return ans;
    }
};
```
```Java []
class Solution {
    public String baseNeg2(int n) {
        String ans = "";
        int t = 0, sum = 0;

        if(n==0)
            return "0";
            
        while (n != 0) 
        {
            int rem = n % (-2);
            n = n / (-2);

            if (rem < 0) 
            {
                n = n + 1;
                rem = rem + 2;
            }

            ans = (rem + "") + ans;
        }

        return ans;
    }
}
```
---
![sution section image.jpeg](https://assets.leetcode.com/users/images/d95f34ac-101c-4113-938b-317325a3413e_1737993471.1954193.jpeg)



['Math', 'String', 'C++', 'Java']