华为机试题-超长正整数相加

#include <iostream>
#include <string>
using namespace std;
// 输入参数:
// char * pcAddend:加数
// char * pcAugend:被加数
// char * pcAddResult:加法结果
void AddLongInteger(char * pcAddend, char * pcAugend, char * pcAddResult)
{
     int length1 = strlen(pcAddend);
     int length2 = strlen(pcAugend);
     int carry_bit =0; //记录有无进位
     int a1 = 0;
     int a2 = 0;
     int i = length1-1;
     int j = length2-1;
     string s="";
     for(;i>=0||j>=0;i--,j--)
     {
          if(i>=0)
          {
               a1 = pcAddend[i]-'0';
          }
          else
          {
               a1 = 0;
          }
          if(j>=0)
          {
               a2 = pcAugend[j]-'0';
          }
          else
          {
               a2 = 0;
          }
          int sum = a1+a2+carry_bit;
          if(sum>=10)
          {
               carry_bit = 1;
               sum -= 10;
          }
          else
          {
               carry_bit = 0;
          }
          char temp = sum +'0';
          // cout<<temp<<endl;
          s = temp+s;
     }
     if(carry_bit==1)
          s = '1'+s;
     // cout<<s<<endl;
    
     pcAddResult = new char[s.length()+1];
     strcpy(pcAddResult,s.c_str());  //将字符串的值拷贝给字符数组
     pcAddResult[s.length()] ='\0';
     cout<<pcAddResult<<endl;
}

int main(){
     string s1,s2;
     cin>>s1;
     cin>>s2;
     char *a,*b,*c;
     a = new char[s1.length()+1];
     strcpy(a,s1.c_str());
     a[s1.length()] ='\0';
     b = new char[s2.length()+1];
     strcpy(b,s2.c_str());
     b[s2.length()] ='\0';
     AddLongInteger(a,b,c);
     // cout<<c<<endl;
     // cout<<a<<endl;
}
题是做对了,但是感觉代码比较乱,请多提意见!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值