从10到6的转换

时间:2019-07-18 06:19:19

标签: c logic base base-conversion

我试图将C中的以10为底的数字转换为以6为底的数字,但是我的代码没有通过2个隐藏的测试用例。

我在其中找不到任何逻辑错误。

可以吗?

//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);

}

2 个答案:

答案 0 :(得分:3)

您的解决方案仅在int的有限范围内起作用。

由于以6为底的数字将比以10为底的数字使用更多的数字,所以在某个点,以10为底的数字将生成一个不适合int的以6为底的数字,从而产生溢出。

请参见this example

一种解决方案是使用字符串生成以6为底的数字。该数字存储在字符数组中。

#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 */
}

输出:

20130035113

答案 1 :(得分:1)

将数字转换为给定的基数应作为字符串完成。

这是一个简单且通用的转换函数:

#include <stdio.h>

char *convert(char *dest, size_t size, int val, int base) {
    static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    char buf[66];
    char *p = buf + sizeof(buf);
    unsigned int n = val;

    if (base < 2 || base > 36 || !dest || size == 0)
        return NULL;
    if (val < 0)
        val = -n;

    *--p = '\0';
    while (n >= base) {
        *--p = digits[n % base];
        n /= base;
    }
    *--p = digits[n];
    if (val < 0)
        *--p = '-';
    if (buf + sizeof(buf) - p > size) {
        buf[size - 1] = '\0';
        return memset(buf, size - 1, '*');
    } else {
        return memcpy(dest, p, buf + sizeof(buf) - p);
    }
}

int main() {
    char buf[32];
    int num;

    while (scanf("%d", &num)) {
        printf("%d -> %s\n", num, convert(buf, sizeof buf, num, 6);
    }
    return 0;
}
相关问题