C ++ addition high-precision algorithms and addition high-precision Algorithms

Source: Internet
Author: User

C ++ addition high-precision algorithms and addition high-precision Algorithms

C ++ high-precision algorithms are a big challenge for beginners. As long as you overcome them, you will start a new chapter in programming, algorithms.

The code I sent is not very good, it occupies a lot of memory and runs for a long time (no more than 1 second), but it is very understandable and suitable for beginners.

The essence of high-precision algorithms is to program strings in arrays, and then add strings as vertical:

1 # include <iostream> 2 # include <cmath> 3 # include <cstring> 4 using namespace std; 5 int main () 6 {7 char a [100010], B [100010]; 8 cin> a> B; // enter two strings. 9 int c [100010], d [100010], h [100010], n1, n2, I, jw = 0; // set three positive integer arrays, to store two processors, one for storage and one for storage. N1n2 stores the length of string a and string B. 10 n1 = strlen (a); // Save the length of string a to 11 n2 = strlen (B); 12 for (I = 0; I <n1/2; I ++) swap (a [I], a [n1-1-i]); // swap the order of the addition string so that you can align, just like an addition vertical. 13 for (I = 0; I <n2/2; I ++) swap (B [I], B [n2-1-i]); // same as 14 for (I = 0; I <n1; I ++) c [I] = a [I]-'0'; // converts string c to array, -'0' indicates the Conversion Method 15 for (I = 0; I <n2; I ++) d [I] = B [I]-'0 '; 16 if (n1> n2) swap (n1, n2); // compare the length of two arrays and select a long for loop condition. 17 for (I = 0; I <n2; I ++) h [I] = c [I] + d [I]; 18 for (I = 0; I <n2; I ++) 19 {20 if (h [I]> = 10) 21 {22 jw = h [I]/10; // take carry 23 h [I] = h [I]-10; // remove carry 24 h [I + 1] ++; 25} 26 if (jw> 0) 27 {28 jw = 0; // initialize carry 29} 30} 31 if (h [n2]! = 0) cout

 

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.