I tried to convert a base 10 number to base 6 in C, but my code didn't pass 2 hidden test cases.
I can't find any logical error in it.
Could you?
//convert base 10 to base 6
#include<stdio.h>
int main()
{
int num, rem = 0, i = 1, res = 0;
scanf("%d", &num);
while(num!=0)
{
rem = num%6;
res = (rem*i)+res;
num = num/6;
i = i*10;
}
printf("%d",res);
}
Your solution will only work for a limited range of int
.
Since base 6 will use more digits than a base 10 number, there will be a point where the base 10 number will generate a base 6 number that will not fit into an int
, thus producing an overflow.
See this example.
One solution is to use strings to generate the base 6 number. The number is stored in a character array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
const int maxdigits = 26; /* max number of base 6 digits for a 64 bit int */
int num=123456789, rem = 0;
/* handle negative input */
int tempnum = abs(num);
int lastpos = maxdigits-1;
/* initialize array, and initialize array to spaces */
char res[maxdigits + 1];
memset(res, ' ', maxdigits);
/* null terminate */
res[maxdigits] = 0;
do
{
rem = tempnum % 6;
res[lastpos--] = rem + '0'; /* set this element to the character digit */
tempnum /= 6;
} while (tempnum > 0);
printf("%s%s", (num < 0)?"-":"", res + lastpos + 1); /* print starting from the last digit added */
}
Output:
20130035113