Python realizes high-precision addition calculation

Keywords: Python Algorithm


Title Source: Central Europe 2000
Question No.: ZOJ1205

Topic Description: addition of decimal large numbers

Enter description
Output description


analysis:

1. First, we need to determine how many arrays we need to receive

Here is the first input method we traditionally define, which is direct input

n=int(input()) # Indicates that there are n groups of input data

2. Process a set of numbers

2.1 the first is to store the input numbers

As mentioned in the title, the length of integers will not be greater than 100, so we can use int or str to store each digit here. Because the length of numbers is not fixed, we should establish a list with a length of 100 to ensure that it can be stored. For the convenience of later calculation, we should store them in reverse order. If they are stored in positive order, it is not convenient for calculation, And it's easy to calculate misalignment. So the first bit should be the single digit of the representation (I use the int type to store our value here)
The code is as follows

x = []
maxlen = -1
for n in range(100):
    Num = input()
    if (Num == "0"):
        break
    x.append([0 for i in range(100)])  # Add a storage location
    lens = len(Num)
    # Gets the length of the longest string
    if lens > maxlen:
        maxlen = lens
    # Store numbers in reverse order
    for S in range(lens):
        x[n][S] = int(Num[lens - 1 - S])

2.2 calculation

Calculate all the numbers. Note that in order to ensure that the calculation is not missing, it is necessary to calculate two more positions on the length of the longest number
1. Name the carry digits, and then calculate the value of each digit from the value of sum, in which the carry digits must be added
2. Then the carry digit is the value of sum divided by 10, and the remainder is the value of the current bit
The code is as follows:

carry = 0  # Represents the value of the carry
for i in range(maxlen + 2):
     sum = carry
     for j in range(n):
         sum += x[j][i]
     digit = sum % 10
     carry = sum // 10
     result[i] = digit

2.3 output

It should be noted that we should determine the output length here. In our results, the first value in reverse order is not 0, so we need to judge whether it is 0 from maxlen+2 of result, find the first value that is not 0, remember this position, and then output from this position
The code is as follows:

i = maxlen + 2
 while (i >= 0):
     if result[i] != 0:
         break
     i -= 1
 while (i >= 0):
     print(result[i], end='')
     i -= 1
 print()

3. Process all arrays

Because the topic mentioned that our output between two arrays needs to be separated by blank lines, we are using to judge whether we need input.

4 complete code

class solution:
    def Integer_solver(self):
        x = []
        sum = 0
        maxlen = -1
        result = [0 for i in range(110)]
        # 1. Receive input value:
        for n in range(100):
            Num = input()
            if (Num == "0"):
                break
            x.append([0 for i in range(110)])  # Add a storage location
            lens = len(Num)
            # Gets the length of the longest string
            if lens > maxlen:
                maxlen = lens
            # Store numbers in reverse order
            for S in range(lens):
                x[n][S] = int(Num[lens - 1 - S])
        carry = 0  # Represents the value of the carry
        for i in range(maxlen + 2):
            sum = carry
            for j in range(n):
                sum += x[j][i]
            digit = sum % 10
            carry = sum // 10
            result[i] = digit
        i = maxlen + 2
        while (i >= 0):
            if result[i] != 0:
                break
            i -= 1
        while (i >= 0):
            print(result[i], end='')
            i -= 1
        print()
    def Integer(self):
        """
        The first line of the input file is an integer N,Indicates that there is a following in the input file N Group data.
        Each group of data contains up to 100 rows. Each line consists of a very long decimal integer,
        The length of this integer will not exceed 100 characters and only contains numbers. The last line of each group of data is 0,
        Indicates the end of this set of data. There is a blank row between each group of data.
        :return:
        """
        n=int(input()) # Indicates that there are n groups of input data

        for i in range(n):
            self.Integer_solver()
            if(i<n):
                print("\n")


if __name__=="__main__":
    A=solution()
    A.Integer()

This is the end of sharing. If you have any questions, you can confide in me. Let's study together. I will try my best to start a column on Algorithm and share my learning experience with you while I study.

Posted by CBG on Tue, 16 Nov 2021 20:58:02 -0800