标签:length 数据结构 == iostream include end style namespace class
倒序存高精度整数,从个位开始对齐。输出时也倒序输出。
1.加法
1 #include<iostream> 2 #include<cmath> 3 #include<string> 4 using namespace std; 5 string str1,str2; 6 int a[255],b[255]; 7 int main(){ 8 ios::sync_with_stdio(false); 9 cin>>str1>>str2; 10 a[0]=str1.length(); 11 b[0]=str2.length(); 12 for (int i=1; i<=a[0]; i++) a[i]=str1[a[0]-i]-‘0‘; 13 for (int i=1; i<=b[0]; i++) b[i]=str2[b[0]-i]-‘0‘; 14 int len=max(a[0],b[0]); 15 for (int i=1; i<=len; i++) { 16 a[i]+=b[i]; 17 a[i+1]+=a[i]/10; 18 a[i]%=10; 19 } 20 ++len; 21 while ((len>1) && (a[len]==0)) --len; 22 for (int i=len; i>0; i--) cout<<a[i]; 23 cout<<endl; 24 return 0; 25 }
2.减法
1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 #include<string> 5 using namespace std; 6 string str1,str2; 7 int a[255],b[255]; 8 int bigger(string x,string y){ 9 int lenx=x.length(); 10 int leny=y.length(); 11 if (lenx>leny) return 1; 12 if (lenx<leny) return -1; 13 for (int i=0; i<lenx; i++){ 14 if (x[i]>y[i]) return 1; 15 if (x[i]<y[i]) return -1; 16 } 17 return 0; 18 } 19 int main(){ 20 ios::sync_with_stdio(false); 21 cin>>str1>>str2; 22 a[0]=str1.length(); 23 b[0]=str2.length(); 24 for (int i=1; i<=a[0]; i++) a[i]=str1[a[0]-i]-‘0‘; 25 for (int i=1; i<=b[0]; i++) b[i]=str2[b[0]-i]-‘0‘; 26 if (bigger(str1,str2)==1) { 27 for (int i=1; i<=a[0]; i++) { 28 a[i]-=b[i]; 29 if (a[i]<0) --a[i+1],a[i]+=10; 30 } 31 a[0]++; 32 while (a[a[0]]==0 && a[0]) --a[0]; 33 for (int i=a[0]; i>0; i--) cout<<a[i]; 34 cout<<endl; 35 } 36 else if (bigger(str1,str2)==-1){ 37 cout<<"-"; 38 for (int i=1; i<=b[0]; i++) { 39 b[i]-=a[i]; 40 if (b[i]<0) --b[i+1],b[i]+=10; 41 } 42 b[0]++; 43 while (b[b[0]]==0 && b[0]) --b[0]; 44 for (int i=b[0]; i>0; i--) cout<<b[i]; 45 cout<<endl; 46 } 47 else cout<<"0"<<endl; 48 return 0; 49 }
3.乘法
1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 #include<string> 5 using namespace std; 6 string str1,str2; 7 int a[255],b[255],ans[555]; 8 int main(){ 9 ios::sync_with_stdio(false); 10 cin>>str1>>str2; 11 a[0]=str1.length(); 12 b[0]=str2.length(); 13 for (int i=1; i<=a[0]; i++) a[i]=str1[a[0]-i]-‘0‘; 14 for (int i=1; i<=b[0]; i++) b[i]=str2[b[0]-i]-‘0‘; 15 for (int i=1; i<=a[0]; i++) 16 for (int j=1; j<=b[0]; j++) { 17 ans[i+j-1]+=a[i]*b[j]; 18 ans[i+j]+=ans[i+j-1]/10; 19 ans[i+j-1]%=10; 20 } 21 int len=a[0]+b[0]+1; 22 while (ans[len]==0 && len>1) --len; 23 for (int i=len; i>0; i--) cout<<ans[i]; 24 cout<<endl; 25 return 0; 26 }
标签:length 数据结构 == iostream include end style namespace class
原文地址:https://www.cnblogs.com/moerblack/p/10483074.html