大数相加和大数相乘以及打印从1到最大的n位数
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
better:
一位一位相加,然后算和算进位,最后根据进位情况看需不需要补一个高位
string addStrings(string num1, string num2) { string res = ""; int m = num1.size(), n = num2.size(), i = m - 1, j = n - 1, carry = 0; while (i >= 0 || j >= 0) { int a = i >= 0 ? num1[i--] - '0' : 0; int b = j >= 0 ? num2[j--] - '0' : 0; int sum = a + b + carry; res.insert(res.begin(), sum % 10 + '0'); carry = sum / 10; } return carry ? "1" + res : res; }
大数相乘
class Solution { public: string multiply(string num1, string num2) { int n=num1.size(); int m=num2.size(); vector<int>temp(n+m,0);//一个m位和n位数相乘得到的数最多是n+m位 for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ temp[i+j+1]+=(num1[i]-'0')*(num2[j]-'0'); } } int bi=0; for(int i=temp.size()-1;i>=0;i--){ temp[i]=temp[i]+bi; bi=temp[i]/10; temp[i]=temp[i]%10; } int i = 0; while (temp[i] == 0)i++;//跳过前面多余的0 if(i>=temp.size())return "0"; string res=""; for(;i<temp.size();i++){ res+=temp[i]+'0'; } return res; } };
打印从1到最大n位数
#include<iostream> #include<string> #include<vector> using namespace std; bool stop(string &str){ bool stop = false; int i = str.size() - 1; int carry = 0; while (i >= 0){ int tmp = str[i] - '0' + carry; if (i == str.size() - 1)tmp++; if (tmp >=10){ if (i == 0){ stop = true; } else{ str[i] = tmp % 10 + '0'; carry = tmp / 10; i--; } } else{ str[i] = tmp + '0'; break; } } return stop; } void print(string &str){ bool flag = false; string res; for (int i = 0; i < str.size(); i++){ if (str[i] == '0'&&flag == false)continue; else if (str[i] != '0'&&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,'0'); while (!stop(res)){ print(res); } } int main(){ int n = 3; PrintNumber(n); system("pause"); return 0; }