
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Convert one base number system to another base system in MySQL
- Convert the string of any base to integer in JavaScript
- Convert from any base to decimal and vice versa in C++
- Convert one base to other bases in a single Java Program
- How to convert a string of any base to an integer in JavaScript?
- How to convert an image to Base 64 string on Android?
- Convert a number into negative base representation in C++
- Convert all substrings of length ‘k’ from base ‘b’ to decimal in C++
- How to get base 2 logarithm of E in JavaScript?
- Compute the logarithm base 2 with scimath in Python
- C++ Program to calculate the base 2 logarithm of the given value
- Haskell Program to calculate the base 2 logarithm of the given value
- Return the base 2 logarithm of the input array in Python
- Return the base 2 logarithm for complex value input in Python
- Convert $2frac{1}{5} hours$ in minutes.

Advertisements