HDOJ1002-A + B Problem II(高精加)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDOJ1002-A + B Problem II(高精加)相关的知识,希望对你有一定的参考价值。
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 ? Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
Means:
求大整数的A+B
Solve:
高精模板题
Code:
1 //仅当两个都为正 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 7 struct big_number 8 { 9 int digit[10000]; 10 int len; 11 big_number() 12 { 13 memset(digit,0,sizeof(digit)); 14 len=0; 15 } 16 }; 17 18 big_number reset_number(char *in)//将低位存在数组前面,如123存到数组里就是321 19 { 20 big_number after; 21 after.len=strlen(in); 22 for(int i=0;i<after.len;++i) 23 { 24 after.digit[i]=(in[after.len-i-1]-48); 25 } 26 return after; 27 } 28 29 big_number add(big_number num1,big_number num2) 30 { 31 int carry=0; 32 big_number ans; 33 for(int i=0;i<num1.len || i<num2.len;++i) 34 { 35 int temp=num1.digit[i]+num2.digit[i]+carry; 36 ans.digit[ans.len++]=temp%10; 37 carry=temp/10; 38 } 39 if(carry!=0) 40 ans.digit[ans.len++]=carry; 41 return ans; 42 } 43 44 int main() 45 { 46 47 int t; 48 scanf("%d" , &t); 49 for(int c = 1 ; c <= t ; ++c) 50 { 51 //printf("%s\n%s\n",in1,in2); 52 char in1[10000]={‘\0‘},in2[10000]={‘\0‘}; 53 scanf("%s%s",in1,in2); 54 big_number change1=reset_number(in1); 55 big_number change2=reset_number(in2); 56 big_number ans=add(change1,change2); 57 printf("Case %d:\n" , c); 58 printf("%s + %s = " , in1 , in2); 59 for(int i=ans.len-1;i>=0;--i) 60 { 61 printf("%d",ans.digit[i]); 62 } 63 if(c != t) 64 printf("\n\n"); 65 else 66 printf("\n"); 67 } 68 return 0; 69 }
以上是关于HDOJ1002-A + B Problem II(高精加)的主要内容,如果未能解决你的问题,请参考以下文章
HDU 1002 A - A + B Problem II (大数问题)