Convert a number into negative base representation

22 Jun, 2022
A number n and a negative base negBase is given to us, we need to represent n in that negative base. Negative base works similar to positive base. For example in base 2 we multiply bits to 1, 2, 4, 8 and so on to get actual number in decimal. In case of base -2 we need to multiply bits with 1, -2, 4, -8 and so on to get number in decimal. Examples:  
Input  : n = 13, negBase = -2
Output : 11101
1*(16) + 1*(-8) + 1*(4) + 0*(-2) + 1*(1)  = 13
It is possible to represent a number into any negative base with same procedure (Refer Wiki for details). For simplicity (to get rid of A, B etc characters in output), we are allowing our base to be in between -2 and -10 only.  
We can solve this problem similar to solving problem with positive bases but one important thing to remember is, remainder will always be positive whether we work with positive base or negative base but in most compilers, the result of dividing a negative number by a negative number is rounded towards 0, usually leaving a negative remainder. So whenever we get a negative remainder, we can convert it to positive as below,  
Let 
n = (?negBase) * quotient + remainder 
  = (?negBase) * quotient + negBase ? negBase + negBase 
  = (?negBase) * (quotient + 1) + (remainder + negBase). 

So if after doing "remainder = n % negBase" and 
"n = n/negBase", we get negative remainder, we do 
following.
remainder = remainder + (-negBase)
n = n + 1

Example : n = -4, negBase = -3
In C++, we get
    remainder = n % negBase = -4/-3 = -1
    n = n/negBase [Next step for base conversion]
      = -4/-3 
      = 1
To avoid negative remainder, we do,
    remainder = -1 + (-negBase) = -1 - (-3) = 2
    n = n + 1 = 1  + 1 = 2.
So when we will get negative remainder, we will make it positive by adding absolute value of base to it and adding 1 to our quotient.Above explained approach is implemented in below code, 
C++
Java
Python3
C#
Javascript
//  C/C++ program to convert n into negative base form#include <bits/stdc++.h>using namespace std; //  Utility method to convert integer into stringstring toString(int n){    string str;    stringstream ss;    ss << n;    ss >> str;    return str;} // Method to convert n to base negBasestring toNegativeBase(int n, int negBase){    //  If n is zero then in any base it will be 0 only    if (n == 0)        return "0";     string converted = "";    while (n != 0)    {        // Get remainder by negative base, it can be        // negative also        int remainder = n % negBase;        n /= negBase;         // if remainder is negative, add abs(base) to        // it and add 1 to n        if (remainder < 0)        {            remainder += (-negBase);            n += 1;        }         // convert remainder to string add into the result        converted = toString(remainder) + converted;    }     return converted;} //  Driver code to test above methodsint main(){    int n = 13;    int negBase = -2;     cout << toNegativeBase(n, negBase);     return 0;}
// Java program to convert n into// negative base formclass GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){    // If n is zero then in any base    // it will be 0 only    if (n == 0)        return "0";     String converted = "";    while (n != 0)    {        // Get remainder by negative base,        // it can be negative also        int remainder = n % negBase;        n /= negBase;         // if remainder is negative,        // add Math.abs(base) to it        // and add 1 to n        if (remainder < 0)        {            remainder += (-negBase);            n += 1;        }         // convert remainder to String add into the result        converted = String.valueOf(remainder) + converted;    }    return converted;} // Driver Codepublic static void main(String[] args){    int n = 13;    int negBase = -2;     System.out.print(toNegativeBase(n, negBase));}} // This code is contributed by 29AjayKumar
# Python 3 program to convert n into# negative base form # Method to convert n to base negBasedef toNegativeBase(n, negBase):         # If n is zero then in any base it    # will be 0 only    if (n == 0):        return "0"     converted = "01"    while (n != 0):                 # Get remainder by negative base,        # it can be negative also        remainder = n % (negBase)        n = int(n/negBase)         # if remainder is negative, add        # abs(base) to it and add 1 to n        if (remainder < 0):            remainder += ((-1) * negBase)            n += 1         # convert remainder to string add        # into the result        converted = str(remainder) + converted             return converted # Driver Codeif __name__ == '__main__':    n = 13    negBase = -2     print(toNegativeBase(n, negBase)) # This code is contributed by# Surendra_Gangwar
// C# program to convert n into// negative base formusing System; class GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){    // If n is zero then in any base    // it will be 0 only    if (n == 0)        return "0";     String converted = "";    while (n != 0)    {        // Get remainder by negative base,        // it can be negative also        int remainder = n % negBase;        n /= negBase;         // if remainder is negative,        // add Math.Abs(base) to it        // and add 1 to n        if (remainder < 0)        {            remainder += (-negBase);            n += 1;        }         // convert remainder to String add into the result        converted = String.Join("", remainder) + converted;    }    return converted;} // Driver Codepublic static void Main(String[] args){    int n = 13;    int negBase = -2;     Console.Write(toNegativeBase(n, negBase));}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to convert n into// negative base form // Method to convert n to base negBasefunction toNegativeBase(n, negBase){    // If n is zero then in any base    // it will be 0 only    if (n == 0)        return "0";     let converted = "01";    while (n != 0)    {        // Get remainder by negative base,        // it can be negative also        let remainder = (-1)*(Math.abs(n) % Math.abs(negBase));         n = parseInt(n/negBase);         // if remainder is negative,        // add Math.abs(base) to it        // and add 1 to n        if (remainder < 0)        {            remainder += ((-1)*negBase);            n += 1;        }         // convert remainder to String add into the result        converted = remainder.toString() + converted;     }    return converted;} // Driver Code let n = 13;let negBase = -2; document.write(toNegativeBase(n, negBase),"</br>"); // This code is contributed by shinjanpatra </script>
Output:  
11101
Time Complexity: O(N)Auxiliary Space: O(1) Reference : https://en.wikipedia.org/wiki/Negative_baseThis article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
SURENDRA_GANGWAR
Harshit Singhal 2
29AjayKumar
Rajput-Ji
aditya_panwar
pankajsharmagfg
shinjanpatra
base-conversion
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between NP hard and NP complete problem
What Should I Learn First: Data Structures or Algorithms?
Ternary Search
Find maximum meetings in one room
K means Clustering - Introduction