用数据结构python写大数计算器

2024-01-07 23:28:48

下面是一个基于Python的大数计算器的示例代码:

class BigNumberCalculator:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    @staticmethod
    def add(num1, num2):
        result = ''
        carry = 0
        len1, len2 = len(num1), len(num2)
        max_len = max(len1, len2)
        
        for i in range(max_len):
            digit1 = int(num1[len1 - 1 - i]) if i < len1 else 0
            digit2 = int(num2[len2 - 1 - i]) if i < len2 else 0
            
            temp_sum = digit1 + digit2 + carry
            carry = temp_sum // 10
            digit_sum = temp_sum % 10
            
            result = str(digit_sum) + result
            
        if carry > 0:
            result = str(carry) + result
        
        return result

    @staticmethod
    def multiply(num1, num2):
        result = ''
        len1, len2 = len(num1), len(num2)
        product = [0] * (len1 + len2)
        
        for i in range(len1-1, -1, -1):
            for j in range(len2-1, -1, -1):
                digit1 = int(num1[i])
                digit2 = int(num2[j])
                
                temp_product = digit1 * digit2 + product[i+j+1]
                product[i+j+1] = temp_product % 10
                product[i+j] += temp_product // 10
        
        for digit in product:
            result += str(digit)
        
        result = result.lstrip('0')
        if not result:
            result = '0'
        
        return result

# 使用示例
num1 = '12345678901234567890'
num2 = '98765432109876543210'

calculator = BigNumberCalculator(num1, num2)

add_result = calculator.add(num1, num2)
print(f'Addition: {num1} + {num2} = {add_result}')

multiply_result = calculator.multiply(num1, num2)
print(f'Multiplication: {num1} x {num2} = {multiply_result}')

这个示例代码定义了一个名为BigNumberCalculator的类,其中包含了两个静态方法addmultiplyadd方法用于实现大数相加,multiply方法用于实现大数相乘。

通过

文章来源:https://blog.csdn.net/LX200384/article/details/135397228
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。