高精度加法(A+B問題)
阿新 • • 發佈:2018-12-12
A+B,作為演算法競賽中最難的一題(霧),總是吸引著廣大程式設計師想盡一切演算法想要去AC它:
這裡提供一種高精度的做法:
#include <iostream> #define maxn 10000000 + 5 using namespace std; string in; int a[maxn], b[maxn], c[maxn];//分別為兩個加數、和 int l1, l2, l3;//三個陣列的長度 void turn(string in, int a[], int &n){ int i = 0, tmp = false; if(in[0] == '-') {i = 1; tmp = true;}//判斷負數 n = in.size(); for(; i < n; i++){ a[n - i - 1] = in[i] - '0'; }//把輸入數的最高位放在陣列的最低位 if(tmp) for(int i = 0; i < n; i++) a[i] = -a[i];//減一個數等於加這個數的相反數 } void _add(){ l3 = max(l1, l2);//和的陣列的長度 for(int i = 0; i < l3; i++){ c[i] = a[i] + b[i]; }//首先進行加法運算 for(int i = 0; i < l3; i++){ if(c[i] >= 10){ c[i + 1] += c[i] / 10; c[i] %= 10; }//正數運算時,考慮進位問題 if(c[i] < 0){ c[i + 1] -= c[i] / 10 + 1; c[i] = 10 + c[i]; }//負數運算時,考慮退位問題 } l3 = l3 + (c[l3] ? 1 : 0);//判斷最高位是否進位 } void print(int a[], int l){ int tmp = false; for(int i = l - 1; i >= 0; i--){ if(!tmp && !a[i] && i) continue; else tmp = true; cout << a[i]; } cout << endl; }//倒過來輸出 int main(){ ios::sync_with_stdio(false); cin >> in; turn(in, a, l1); cin >> in; turn(in, b, l2);//輸入及初始化 _add(); print(c, l3); return 0; }
瀟灑地結束~