51Nod - 1005 大数加法

xiaoxiao2021-02-28  104

1005 大数加法 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 给出2个大整数A,B,计算A+B的结果。 Input 第1行:大数A 第2行:大数B (A,B的长度 <= 10000 需注意:A B有可能为负数) Output 输出A + B Input示例 68932147586 468711654886 Output示例 537643802472 写的稍微麻烦了点但应该很好理解。。 #include<iostream> #include<algorithm> #include<cstring> #include<cstdio> using namespace std; void func(char *a,char *b)//字符换位 { char t=*a; *a=*b; *b=t; } void func0(char *s)//去除字符串首字符 { int n=strlen(s); for(int i=1; i<n; i++) s[i-1]=s[i]; s[n-1]='\0'; } void func1(char *s)//字符串倒置 { int n=strlen(s); for(int i=0; i<=(n-1)/2; i++) func(s+i,s+n-i-1); } bool func2(char *s1,char *s2)//字符串数值大小对比 { int n1=strlen(s1),n2=strlen(s2); if(n1!=n2) return n1>n2; else for(int i=0; i<n1; i++) if(s1[i]!=s2[i]) return s1[i]>s2[i]; return 1; } char *func3(char *S1,char *S2)//大数加法(无符号) { char s1[10008],s2[10008],com[10008]; if(func2(S1,S2)) { strcpy(s1,S1); strcpy(s2,S2); } else { strcpy(s1,S2); strcpy(s2,S1); } int n1=strlen(s1),n2=strlen(s2); for(int i=0; i<10008; i++) com[i]='0'; func1(s1); func1(s2); for(int i=0; i<n2; i++) { int t=s1[i]+s2[i]+com[i]-144; com[i]=48+t; com[i+1]+=t/10; } for(int i=n2; i<n1; i++) { int t=s1[i]+com[i]-96; com[i]=48+t; com[i+1]+=t/10; } if(com[n1]=='0') com[n1]='\0'; else com[n1+1]='\0'; func1(com); return com; } char *func4(char *S1,char *S2)//大数减法(无符号) { char s1[10008],s2[10008],com[10008]; if(func2(S1,S2)) { strcpy(s1,S1); strcpy(s2,S2); } else { strcpy(s1,S2); strcpy(s2,S1); } int n1=strlen(s1),n2=strlen(s2); for(int i=0; i<10008; i++) com[i]='0'; func1(s1); func1(s2); for(int i=0; i<n2; i++) { int t=s1[i]-s2[i]+com[i]-48; if(t<0) { com[i+1]-=1; t+=10; } com[i]=t+48; } for(int i=n2; i<n1; i++) { int t=s1[i]+com[i]-96; if(t<0) { com[i+1]-=1; t+=10; } com[i]=48+t; } for(int i=n1; i>=0; i--) if(com[i]=='0') com[i]='\0'; else break; func1(com); return com; } void func5(char *S1,char *S2)//大数减法及输出(有符号) { char s1[10008],s2[10008]; strcpy(s1,S1); strcpy(s2,S2); char ans[10008],t1=s1[0],t2=s2[0]; if(t1=='+'||t1=='-') func0(s1); if(t2=='+'||t2=='-') func0(s2); if(t1=='-'&&t2=='-') { printf("-"); strcpy(ans,func3(s1,s2)); } if(t1!='-'&&t2=='-') { strcpy(ans,func4(s1,s2)); if(!func2(s1,s2)) printf("-"); } if(t1=='-'&&t2!='-') { strcpy(ans,func4(s2,s1)); if(func2(s1,s2)) printf("-"); } if(t1!='-'&&t2!='-') strcpy(ans,func3(s1,s2)); int n=strlen(ans); for(int i=0; i<n; i++) printf("%c",ans[i]); printf("\n"); } int main() { char s1[10008],s2[10008]; while(~scanf("%s%s",s1,s2)) func5(s1,s2); return 0; }
转载请注明原文地址: https://www.6miu.com/read-42862.html

最新回复(0)