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, '');
//cout << b << endl;
}
else{
nlength = b.size();
diff = b.size() - a.size();
a.insert(a.begin(), diff, '');
//cout << a << endl;
}
//cout << a << endl;
//cout << b << endl;
//cout << c << endl;
int takeover = ;
for (int i = nlength - ; i >= ; i--){
int temp = a[i]-'' + b[i] - '' + takeover;
cout << a[i] << " " << b[i] << endl;
cout << temp << endl;
if (temp >= ){
takeover = ;
b[i] = temp + '' - ; //cout << c[j] << endl;
}
else{
b[i] = temp + '';
takeover = ; }
}
//cout << takeover<<" " << j << endl;
if (takeover == )b = '' + b;
return b;
} void print(string str){
int count = ;
for (int i = ; i < str.size(); i++){
if (str[i] == '')count++;
else
break;
}
cout << str.substr(count, str.size() - count) << endl;;
}

注:char a='9';

int b=a-'0';

a的范围只能是0到9

better:

一位一位相加,然后算和算进位,最后根据进位情况看需不需要补一个高位

string addStrings(string num1, string num2) {
string res = "";
int m = num1.size(), n = num2.size(), i = m - , j = n - , carry = ;
while (i >= || j >= ) {
int a = i >= ? num1[i--] - '' : ;
int b = j >= ? num2[j--] - '' : ;
int sum = a + b + carry;
res.insert(res.begin(), sum % + '');
carry = sum / ;
}
return carry ? "" + res : res;
}

大数相乘

class Solution {
public:
string multiply(string num1, string num2) {
int n=num1.size();
int m=num2.size();
vector<int>temp(n+m,);//一个m位和n位数相乘得到的数最多是n+m位
for(int i=n-;i>=;i--){ for(int j=m-;j>=;j--){
temp[i+j+]+=(num1[i]-'')*(num2[j]-'');
}
}
int bi=;
for(int i=temp.size()-;i>=;i--){
temp[i]=temp[i]+bi;
bi=temp[i]/;
temp[i]=temp[i]%;
}
int i = ;
while (temp[i] == )i++;//跳过前面多余的0
if(i>=temp.size())return "";
string res="";
for(;i<temp.size();i++){
res+=temp[i]+'';
} return res;
}
};

打印从1到最大n位数

#include<iostream>
#include<string>
#include<vector>
using namespace std; bool stop(string &str){
bool stop = false;
int i = str.size() - ;
int carry = ;
while (i >= ){
int tmp = str[i] - '' + carry;
if (i == str.size() - )tmp++;
if (tmp >=){
if (i == ){
stop = true;
}
else{
str[i] = tmp % + '';
carry = tmp / ;
i--;
} }
else{
str[i] = tmp + '';
break;
}
}
return stop;
} void print(string &str){
bool flag = false;
string res;
for (int i = ; i < str.size(); i++){
if (str[i] == ''&&flag == false)continue;
else if (str[i] != ''&&flag == false){
flag = true;
res.push_back(str[i]);
}
else{
res.push_back(str[i]);
}
}
cout << res << endl;
}
void PrintNumber(int n){
string res(n,'');
while (!stop(res)){
print(res);
}
}
int main(){
int n = ;
PrintNumber(n);
system("pause");
return ;
}
05-10 15:54