【面试题】两个32位整数相加,和超过32位怎么计算
源
这道题是我大学刚毕业面试的一家企业的笔试题
当然,这个面试没通过,但是现在工作一段时间后,随着c语言使用的越来越熟练就知道怎么解决了.
解法:
我们知道int类型整数为32位,肯定不能直接用运算符+
来写,那样就不是面试题了。
但是可以将这个int类型相加转换为字符串来存储,字符串长度肯定不受这种限制,所以可以用来存放数据
-
将两个int数据最低位相加
-
将相加结果的最低位存到字符串空间中
-
如果相加结果超过10肯定有进位,将进位1相加到下一位
-
重复1-3步骤
代码:
static int get_num_bit(unsigned int n)
{
int ret = 0;
while (n)
{
n /= 10;
ret++;
}
return ret;
}
char *calc_sum(unsigned int a, unsigned int b)
{
int a_len = get_num_bit(a);
int b_len = get_num_bit(b);
int max_len = a_len > b_len ? a_len + 1 : b_len + 1;
char *ret = (char *)malloc(max_len+1);
memset(ret, '\0', max_len+1);
int index = 0;
int temp_a = 0, temp_b = 0;
int temp_sum = 0;
int temp_add = 0;
//printf("{%u, %u, %d, %d}\n", a, b, a_len, b_len); //数据和长度打印
while (a && b)
{
int i = a % 10 + b % 10 + temp_add;
if (i >= 10)
{
temp_sum = i % 10;
ret[index++] = (char)(temp_sum + '0');
temp_add = 1;
}
else
{
ret[index++] = (char)(i + '0');
temp_add = 0;
}
a /= 10;
b /= 10;
}
if (a)
{
while (a)
{
temp_sum = a % 10 + temp_add;
ret[index++] = (char)(temp_sum + '0');
a /= 10;
temp_add = 0;
}
}
if (b)
{
while (b)
{
temp_sum = b % 10 + temp_add;
ret[index++] = (char)(temp_sum + '0');
b /= 10;
temp_add = 0;
}
}
ret[index] = '\0';
return ret;
}
注意:上边的代码只是计算得到的字符串的反串,可以通过下边的函数来进行字符串反转
static char *str_cov(char *str)
{
int len = strlen(str);
int i=0;
char *ret = (char *)malloc(len+1);
memset(ret, '\0', len+1);
for(i=len-1; i>=0; i--)
ret[len-i-1] = str[i];
free(str);
return ret;
}
全部代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int get_num_bit(unsigned int n)
{
int ret = 0;
while (n)
{
n /= 10;
ret++;
}
return ret;
}
static char *str_cov(char *str)
{
int len = strlen(str);
int i=0;
char *ret = (char *)malloc(len+1);
memset(ret, '\0', len+1);
for(i=len-1; i>=0; i--)
ret[len-i-1] = str[i];
free(str);
return ret;
}
char *calc_sum(unsigned int a, unsigned int b)
{
int a_len = get_num_bit(a);
int b_len = get_num_bit(b);
int max_len = a_len > b_len ? a_len + 1 : b_len + 1;
char *ret = (char *)malloc(max_len+1);
memset(ret, '\0', max_len+1);
int index = 0;
int temp_a = 0, temp_b = 0;
int temp_sum = 0;
int temp_add = 0;
//printf("{%u, %u, %d, %d}\n", a, b, a_len, b_len); //数据和长度打印
while (a && b)
{
int i = a % 10 + b % 10 + temp_add;
if (i >= 10)
{
temp_sum = i % 10;
ret[index++] = (char)(temp_sum + '0');
temp_add = 1;
}
else
{
ret[index++] = (char)(i + '0');
temp_add = 0;
}
a /= 10;
b /= 10;
}
if (a)
{
while (a)
{
temp_sum = a % 10 + temp_add;
ret[index++] = (char)(temp_sum + '0');
a /= 10;
temp_add = 0;
}
}
if (b)
{
while (b)
{
temp_sum = b % 10 + temp_add;
ret[index++] = (char)(temp_sum + '0');
b /= 10;
temp_add = 0;
}
}
ret[index] = '\0';
return ret;
}
int main(int argc, const char **argv)
{
unsigned int a = 0xFFFFFFFF;
unsigned int b = 0x11111111;
char *p_sum = calc_sum(a, b);
char *sum = str_cov(p_sum);
printf("sum:%s\n", sum);
return 0;
}
总结:
注意,以上思路跟leetcode的第二题有点相似,但是leetcode第二题是链表形式并且结构是独立的,而上边我是直接申请了一个字符串空间来存。