Thursday, December 22, 2011

Number Conversion

Write a C Program to Convert a given decimal number to any other base (either positive or negative).

Algorithm:
For example, 100 in Base 2 is 1100100 and in Base -2 is 110100100.
Here’s a simple algorithm to convert numbers from Decimal to Negative Bases :

def tonegativeBase(N,B):
   digits = []
   while i != 0:
 i, remainder = divmod (i, B)
 if (remainder < 0):
     i, remainder = i + 1, remainder + B*-1
 digits.insert (0, str (remainder))
   return ''.join (digits)
We can just tweak the above algorithm a bit to convert a decimal to any Base. Here’s a sample code :

Code:

 #include<iostream>
using namespace std;

void convert10tob(int N,int b)
{
     if (N==0)
        return;
   
     int x = N%b;
     N/=b;
     if (x<0)
        N+=1;
      
     convert10tob(N,b);
     printf("%d",x<0?x+(b*-1):x);
}

int main()
{
    int N,b;
    while (scanf("%d%d",&N,&b)==2)
    {
          if (N!=0)
          {
              convert10tob(N,b);
              printf("\n");
          }
          else
              printf("0\n");
    }
}

No comments:

Post a Comment