The problem A+B is probably the easiest problem, however, the maxim number C/C++ can calculate is between -9223372036854775808~9223372036854775807. The bigger number can’t be calculate unless you use Python or Java. So I’m going to introduce a way to calculate the big number of A+B.
Since we can’t use the type int , long int or long long, we can use string to store the big number.
1 | string a, b; |
With string, we can operate bitwise addition we learnt when we are in kindergarten. Started from the last bit and align the ends. It’s easier to insert characters in the front of a string then insert at the end. So we reverse the string.
1 | reverse(a.begin(), a.end()); |
Then we need to know how many digits is the difference between the two numbers and make up the difference with character ‘0’.
1 | int diff = abs((int)(a.length() - b.length())); |
Note that .length() returns a type - unsigned long long, if we directly operate the minus operation, the answer will overflow because unsigned long long can’t be negative.
Then we start to calculate each digit, every digit consist of three element: a[i], b[i], carryIn.
1 | int carryIn = 0, digit; |
If there is still a carryIn when we calculated all the digit, we add a new digit to the number.
1 | if(carryIn){ |
And don’t forget to reverse the answer back.
1 | reverse(ans.begin(), ans.end()); |
Here is a problem of the A+B A + B Problem II
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
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.
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.
1 | 2 |
1 | Case 1: |
1 |
|