Represent a number N in base -2
Last Updated :
23 Jul, 2021
Given an integer N, the task is to find base -2 representation of the number N in the form of a string, such that S0 * (- 2)0 + S1 * (- 2)1 + … + Sk * (- 2)k = N. The string should only consist of 0s and 1s and unless the string is equal to zero, the initial character should be 1.
Examples:
Input: N = -9
Output: 1011
Explanation: 1011 is -2 representation of -9
(-2)0+ (-2)1+ (-2)3 = 1+ (-2) + (-8) = -9
Input: N = -7
Output: 1001
Approach: Follow the steps below to solve the problem:
- Initialize an empty string S.
- Iterate from N, until N is greater than zero.
- If N is even, append ‘0‘ in front of S and divide N by -2.
- Otherwise, append ‘1‘ in front of S, and decrement N by 1, and then divide N by -2.
- If the string S is empty, then return ‘0‘
- Finally, return the string S.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
class GFG {
public static 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;
}
public static void main(String args[]) {
int N = - 9 ;
System.out.println(BaseConversion(N));
}
}
|
Python3
def BaseConversion(N):
s = ""
while (N ! = 0 ):
if (N % 2 = = 0 ):
s = "0" + s
else :
s = "1" + s
N - = 1
N / = - 2
if (s = = ""):
s = "0"
return s
N = - 9
print (BaseConversion(N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static 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;
}
public static void Main()
{
int N = -9;
Console.Write(BaseConversion(N));
}
}
|
Javascript
<script>
function BaseConversion(N)
{
let s = "" ;
while (N != 0) {
if (N % 2 == 0) {
s = "0" + s;
}
else {
s = "1" + s;
N--;
}
N /= -2;
}
if (s == "" ) {
s = "0" ;
}
return s;
}
let N = -9;
document.write(BaseConversion(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...