大数相加
Posted 追逐面包和牛奶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大数相加相关的知识,希望对你有一定的参考价值。
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
以上是关于大数相加的主要内容,如果未能解决你的问题,请参考以下文章