Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
This is for some new college students knowledge points, big god can be directly scratched out.
I believe that those of you who played algorithm competitions in college have already been exposed to large number addition in the beginning. Some people would say, well, don’t you just add plus and you just add?
For example int a; If you add int b, you get int c
If number and small, is indeed can but if the number is: 100000000000000000000000000… Omit hundreds of bits.
Int can’t store anything like that, even if your int64 can only store 2 to the 32nd minus 1, which is already the biggest number, but notice there are negative numbers, so it’s 2 to the 32nd minus 1, not to the 64th. So what do we need to do?
The answer is an array, such as int a[300] can store up to 300 digits.
char s1[M], s2[M]; int num1[M] = {0}; // num1 int num2[M] = {0}; // num2 scanf("%s %s", s1, s2); len_s1 = strlen(s1); Len_s2 = strlen(s2); len_s2 = strlen(s2); // Find the second addendCopy the code
Let’s just go ahead and do it. The M up here is whatever number you define, whatever you want. It’s usually 100 or so, 100 digits, which is pretty scary.
for(i=len_s1-1, j=0; i>=0; Num1 [j] = s1[I] - '0'; num1[j] = s1[I] - '0'; j++; } for(i=len_s2-1, j=0; i>=0; Num2 [j] = s2[I] - '0'; num2[j] = s2[I] - '0'; j++; }Copy the code
To convert a string to a number, you need – ‘0’, and then the most important step is why do you need reverse order? Because we’re adding from right to left, 1000 plus 1000 is adding 0 and 0 first, not 1 and 1 first, so we have to do the reverse order. If you don’t understand it, you can just write down an addition column and see what’s going on.
for(i=0; i<=M; {num1[I] = num1[I]+num2[I]; if(num1[i]>9) { num1[i] = num1[i]-10; num1[i+1]++; }}Copy the code
Num1 [I +1]++; Carry, if this position is a number greater than or equal to 10, then we need to carry. This is just simulating our vertical addition.
Above is the rendering.
In the diagram above, I just wrote two numbers, but more complicated numbers can be calculated.
And then think about it further, in addition to large number addition, we can also do large number subtraction, large number multiplication, large number division and so on. The principle remains the same, just using arrays to simulate the platform’s arithmetic operations.
If we go a little higher, we can do operations with decimals.
You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.