大数相加
#include<iostream> #include<string> #include<algorithm> using namespace std; string add_big_num(string a, string b) { string sum; int pos_a = a.find("."), pos_b = b.find("."),flag=0,temp=0;//没有找到的话返回值为-1,find返回下标,flag进位符 if (pos_a != -1 || pos_b != -1){ //其中一个有小数部分,先补齐小数部分 if (pos_a == -1){ //如果a没有,补一个. a += '.'; pos_a = a.size() - 1; } if (pos_b == -1){ //如果b没有,补一个. b += '.'; pos_b = b.size() - 1; } (a.size() - 1 - pos_a) < (b.size() - 1 - pos_b) ? a.append(b.size() - pos_b - a.size() + pos_a, '0') : b.append(a.size() - pos_a - b.size() + pos_b, '0'); } reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); a.size() < b.size() ? a.append(b.size() - a.size(), '0') : b.append(a.size() - b.size(), '0'); for (int i = 0; i < a.size(); ++i){ temp = 0; if (a[i] == '.')//已经对齐了,a和b小数点的位置一样 sum += '.'; else{ temp = a[i] - '0' + b[i] -'0' + flag; flag = 0; if (temp >= 10) { temp -= 10; sum += temp+'0'; flag = 1; } else sum += temp + '0'; } } if (flag == 1) sum += '1'; reverse(sum.begin(),sum.end()); return sum; } int main() { string a,b; cin >> a >> b; cout << add_big_num(a, b)<<endl; return 0; }大数乘法
string multiply(string num1, string num2) { int len1 = num1.size(),len2 = num2.size(); string res(len1 + len2, '0'); for (int i = len2 - 1; i >= 0; i--) { //从个位开始。注意:数组是从高位到低位存储的,i+j相对i+j+1才是高位! for (int j = len1 - 1; j >= 0; j--) { int temp = (res[i + j + 1] - '0') + (num1[j] - '0')*(num2[i] - '0');//res[i + j + 1] - '0',有可能之前进位了,而且最多只会进位影响一位 res[i + j + 1] = temp % 10 + '0';//当前位.这里是等于,所以要加‘0’ res[i + j] += temp / 10; //前一位加上进位!!!res[i+j]已经初始化为'0',加上int类型自动转化为char,所以此处不加'0' } } //去除首位'0' for (int i = 0; i<len1 + len2; i++) //从高位到低位找0 if (res[i] != '0') return res.substr(i);//从第一个不是0的数截取 return "0"; }