The resulting string must not have leading zeros unless the string is “0”.
If 'N' = 4, then its value in base ‘-2’ will be “100” as 0*(-2)^0 +0*(-2)^1 + 1*(-2)^2 = 4.
The first line contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains a single integer denoting ‘N’.
For each test case, return a string denoting the value of ‘N’ in base ‘-2’.
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 50
0 <= N <= 10^9
Time limit: 1 sec
We can solve this problem as we do for positive bases. The main thing is that remainder should always be a positive number which is the contradicting point in negative bases.
Let us understand this with an example.
Let’s say ‘N’ = -5 and ‘BASE’ = -2. Now on dividing -5 by -2 we will get a quotient = 2 and remainder = -1.
Writing -5 according to remainder formula, we get -5 = 2*(-2) + -1.( dividend = quotient*divisor + remainder)
The remainder should always be positive, and here the remainder is negative.
If we right ‘-5’ as -5 = 3*(-2) + 1, we can get a positive remainder.
We can say that whenever the remainder is negative, we can make it positive by incrementing the quotient by ‘1’ and remainder by ‘2’.
So the idea to convert the given number to base ‘-2’ is the same as we do in base positive ‘2’ with an extra point that whenever the remainder comes negative, we will increment the ‘N’ by ‘1 remainder by ‘2’.
Algorithm