简单的看就是个加减法的问题,需要注意的是值范围,十进制18位以内需要用long long在存值。
两种方法都试了一下,都AC过了。
1)都转换成十进制,然后把和再转成b进制。
#include <stdio.h>
#include <string.h>
unsigned long long cal10(int b, char *s)
{
unsigned long long rlt = 0;
char ch;
while(*s)
{
rlt = rlt * b + ( b > 9 && *s > '9' ? *s - 'A' + 10 : *s - '0');
s++;
}
return rlt;
}
void printrlt(int b, unsigned long long v)
{
char rlt[128];
rlt[127]='\0';
int i = 126;
while (v > 0)
{
rlt[i] = v % b;
if (b > 9 && rlt[i] > 9)
rlt[i] = rlt[i] - 10 + 'A';
else
rlt[i] += '0';
v /= b;
i--;
}
printf("%s\n", rlt+i+1);
}
int main()
{
#ifdef DEBUG_INPUT
freopen("t1003_A+B.in", "r", stdin);
#endif
int b;
char str[100];
int len, i;
unsigned long long v1, v2;
while(EOF != scanf("%d", &b))
{
scanf("%s", str);
v1 = cal10(b, str);
scanf("%s", str);
v2 = cal10(b, str);
printrlt(b, v1+v2);
}
return 0;
}
2)用数组模拟加法。
#include <stdio.h>
#include <string.h>
#define GET_INTV(c) (b > 9 && (c) > '9' ? (c)-'A'+10 : (c)-'0')
#define TO_CHARV(c) (b > 9 && (c) > 9 ? (c)-10+'A' : (c)+'0')
int main()
{
int b, l1, l2, i, ov, t;
char str1[100], str2[100], r[100], c;
r[99] = '\0';
while(EOF != scanf("%d %s %s", &b, str1, str2))
{
i = 98, ov = 0;
l1 = strlen(str1), l2 = strlen(str2);
while(l1 > 0 && l2 > 0)
{
l1--, l2--;
c = GET_INTV(str1[l1]) + GET_INTV(str2[l2]) + ov;
ov = c / b;
c %= b;
r[i--] = TO_CHARV(c);
}
while(l1 > 0)
{
l1--;
c = GET_INTV(str1[l1]) + ov;
ov = c / b;
c %= b;
r[i--] = TO_CHARV(c);
}
while(l2>0)
{
l2--;
c = GET_INTV(str2[l2]) + ov;
ov = c / b;
c %= b;
r[i--] = TO_CHARV(c);
}
while (ov > 0)
{
c = ov % b;
ov = ov / b;
r[i--] = TO_CHARV(c);
}
printf("%s\n", r+i+1);
}
return 0;
}