Convert to Base -2 in C++


Suppose we have a number N, we have to find a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). The returned string should have no leading zeroes, unless the string is exactly "0". So if the input is like 2, then the output will be “110”, as (-2)^2 + (-2)^1 + (-2)^0 = 2.

To solve this, we will follow these steps −

  • ret := an empty string

  • if N = 0, then return “0”

  • while N is non 0

    • rem := N mod (– 2)

    • N := N / (-2)

    • if rem < 0 and rem := rem + 2 and increase N by 1

    • ret := ret + rem as string

  • reverse the string ret

  • return ret.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string baseNeg2(int N) {
      string ret = "";
      if(N == 0) return "0";
      while(N){
         int rem = N % (-2);
         N /= -2;
         if(rem < 0) rem += 2, N++;
         ret += to_string(rem);
      }
      reverse(ret.begin(), ret.end());
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.baseNeg2(17));
}

Input

17

Output

10001

Updated on: 30-Apr-2020

915 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements