C++面试题(实现任意长度的整型数相加)

#include <iostream>

using namespace std;

//可以实现任意长度的两个数相加
char *add(char *num1, char *num2);

int main()
{
     char n2[] = "995623548946456423";
     char n1[] = "9954896431548699";

     char *p = NULL;
     p = add(n1, n2);
 
     if (p[0] == '0')
     {
      cout << "sum is " << &p[1] << endl;
     }
     else
     {
          cout << "sum is " << p << endl;
     }
 
     if (p != NULL)
     {
          delete p;
          p = NULL;
     }
 
     return 0;
}

char *add(char *num1, char *num2)
{
     if (NULL == num1 || NULL == num2)
     {
          return NULL;
     }
 
     int len1 = strlen(num1);
     int len2 = strlen(num2);
 
     //使得num1 为较长的那个数, len1 较大
     if (len1 < len2)
     {
          char *p = num1;
          num1 = num2;
          num2 = p;
  
          int tmp = len2;
          len2 = len1;
          len1 = tmp;
     } 
 
     //用新分配的空间保存结果(初始化之后暂存num1 的值)
     //如果用num1 本身保存,可能存在越界问题
     char *pnum1 = new char[len1+2];
     if (NULL == pnum1)
     {
          return num1;
     }
     memset(pnum1, 0, len1+2);
 
     //防止 两数相加的和越界,在高位预留一位
     pnum1[0] = '0';
     strncpy(&pnum1[1], num1, len1); 
 
     int tmp1, tmp2; 
     for (int i = len1, j = len2 - 1; i >= 0; i--)
     {
          //字符型数据 = 整型数据 + '0';
          tmp1 = pnum1[i] - '0';
  
          //两个加数长度不等时,从最低位开始相加。
          //当位数较少的那个加数、最高位已经加上时, 此时不能再加上它
          if (j >= 0)
          {
               tmp2 = num2[j] - '0'; 
               tmp1 += tmp2;
               j--;
          }
   
          //判断是否需要进位(10进制最大9)
          int t = i;  
          if (tmp1 >= 10)
          {   
               tmp1 -= 10; 
               pnum1[t] = tmp1 + '0';
               pnum1[--t] += 1;
          }
          else
          {
               pnum1[i] = tmp1 + '0';
          }
     }
 
     return pnum1;
}


阅读更多
想对作者说点什么? 我来说一句

C++实现长整数的输入输出

2009年05月30日 4KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭