码迷,mamicode.com
首页 > 其他好文 > 详细

大数相加

时间:2018-05-12 11:53:51      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:break   int   diff   char   begin   insert   else   bst   for   

string add(string a, string b){
    int nlength;
    int diff;
    if (a.size() > b.size()){
        nlength = a.size();
        diff = a.size() - b.size();
        b.insert(b.begin(), diff, 0);
        //cout << b << endl;
    }
    else{
        nlength = b.size();
        diff = b.size() - a.size();
        a.insert(a.begin(), diff, 0);
        //cout << a << endl;
    }
    //cout << a << endl;
    //cout << b << endl;
    //cout << c << endl;
    int takeover = 0;
    for (int i = nlength - 1; i >= 0; i--){
        int temp = a[i]-0 + b[i] - 0 + takeover;
        cout << a[i] << " " << b[i] << endl;
        cout << temp << endl;
        if (temp >= 10){
            takeover = 1;
            b[i] = temp + 0 - 10;
            
            //cout << c[j] << endl;
        }
        else{
            b[i] = temp + 0;
            takeover = 0;
            
        }
    }
    //cout << takeover<<" " << j << endl;
    if (takeover == 1)b = 1 + b;
    return b;
}

void print(string str){
    int count = 0;
    for (int i = 0; i < str.size(); i++){
        if (str[i] == 0)count++;
        else
            break;
    }
    cout << str.substr(count, str.size() - count) << endl;;
}

 注:char a=‘9‘;

        int b=a-‘0‘;

        a的范围只能是0到9

大数相加

标签:break   int   diff   char   begin   insert   else   bst   for   

原文地址:https://www.cnblogs.com/inception6-lxc/p/9028158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!