Computer N-digit addition

Source: Internet
Author: User

# Include <iostream>
# Include <string>
Int main ()
{
Using namespace STD;
String A, B;
Cout <Endl <"input number :";
Cin>;
Cout <"Enter the number B :";
Cin> B;
Int DH/* used to save the sum of each digit in a B and */
, Yu = 0/* is used to save the value to carry */
, AZ = A. Size ()-1, Bz = B. Size ()-1;/* measure the length of a B string minus 1 because the array starts from 0 */
Int bjab = Az> BZ? AZ: Bz; // calculate the length of the string a and B.

Char * P = new char [bjab + 3]; // The requested space for storing the final sum

If (P = NULL)
{
Cout <"insufficient memory ";
Return 0;
}
Int I = 0, Vc = 0, K = 0, JL = 0;
For (I; I <= bjab + 2; I ++)
{

If (! (A [AZ]> = '0' & A [AZ] <= '9' & B [BZ]> = '0' & B [BZ] <= '9 '))
{
Cout <Endl <"the number you entered contains invalid characters! The program will exit "<Endl;
Delete [] P;
Exit (1 );

}
DH = (a [AZ]-'0') + (B [BZ]-'0'); // convert each character in a B to a number and then add it together
P [VC ++] = (DH + Yu) % 10) + '0'; // save DH and single digit
If (DH + Yu = 10) Yu = 1; // this parameter is used to remove the case where DH equals 9 Yu equals 1 and there is no remainder.
Else Yu = DH/10;


If (AZ = 0) A [AZ] = '0'; // when string a is shorter than string B, add 0 if string a is shorter than string B.
Else AZ --;
If (Bz = 0) B [BZ] = '0'; // same as above
Else BZ --;
}
Cout <Endl <"the length of number A is :"
<A. Size () <Endl <"the length of digit B is :"
<B. Size () <Endl;
Cout <Endl <"A + B = ";
If (P [VC-1] = '0' & P [vc-2] = '0') k = vc-3; // remove the case where there is no carry before 0
Else if (P [VC-1] = '0') k = vc-2;
Else
K = VC-1;
For (K; k> = 0; k --) // output characters from the back
Cout <p [k];
Cout <Endl;
Delete [] P;
Return 0;
}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.