Represent a number N in base | C ++ Program for above approach ; Function to convert N to equivalent representation in base - 2 ; Stores the required answer ; Iterate until N is not equal to zero ; If N is Even ; Add char '0' in front of string ; Add char '1' in front of string ; Decrement N by 1 ; Divide N by - 2 ; If string is empty , that means N is zero ; Put '0' in string s ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string BaseConversion ( int N ) { string s = " " ; while ( N != 0 ) { if ( N % 2 == 0 ) { s = "0" + s ; } else { s = "1" + s ; N -- ; } N /= -2 ; } if ( s == " " ) { s = "0" ; } return s ; } int main ( ) { int N = -9 ; cout << BaseConversion ( N ) ; return 0 ; }