编程理解——大数相加

之前听别人说过这道题,昨晚做某家公司的笔试题遇到这个问题,今天面试也遇到这道题了,有时候想这题还真有缘~~~~~~最后彻底搞明白一下。
两个数字的字符串,计算相加之后得到的字符串,当数很大的时候用这种方法计算高效。例如,string a=“453”,string b=“29”,add(a,b)输出“482”。

#include <iostream>
#include <string>
using namespace std;

string add(string a, string b)
{
    string result;
    int i=a.length()-1;
    int j=b.length()-1;
    int c=0;
    int temp=0;
    char s;
    while(i>=0&&j>=0){
        temp=a[i]-'0'+b[j]-'0'+c;
        if(temp<10) {
			s=temp+'0';
			c=0;
		}
        else{
            s=temp%10+'0';
            c=temp/10;
        }
        result.push_back(s);
        i--;
        j--;
    }
	while(c>0){
        if(i<0&&j<0) {
			s=c+'0';
			c=0;
		}
        if(i>=0) {
			temp=a[i]-'0'+c;
			if(temp<10) {
				s=temp+'0';
				c=0;
			}
			else{
				s=temp%10+'0';
				c=temp/10;
			}
			i--;
		}
        if(j>=0) {
			temp=b[j]-'0'+c;
			if(temp<10) {
				s=temp+'0';
				c=0;
			}
			else{
				s=temp%10+'0';
				c=temp/10;
			}
			j--;
		}
		result.push_back(s);
    }
    while(i>=0) {
        s=a[i];
        result.push_back(s);
		i--;
    }
    while(j>=0) {
        s=b[j];
        result.push_back(s);
		j--;
    }

    for(unsigned int k=0;k<result.length()/2;k++){
        s=result[k];
        result[k]=result[result.length()-1-k];
        result[result.length(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值