用链表实现大整数加减法操作: 32 位机器直接操作的数据最大为 32 个 bit,若超过 32bit,则需要单独设计算法。在这 里,可以用链表每个结点存储大整数的每一位的十进制数字,则可以进行大整数的算数运算, 该实验仅实现加减法操作。 要求: 1, 随机产生 2 个 1~50 位的数字串,并存储到 2 个链表中。 2, 进行加法或减法操作,结果存储到新的链表中。 3, 打印运算结果。
时间: 2023-05-26 18:04:45 浏览: 90
以下是用Python实现的代码:
```python
import random
# 定义链表节点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 生成1~50位的数字串,并存储到链表中
def generate_num():
n = random.randint(1, 50)
num = ""
for i in range(n):
num += str(random.randint(0, 9))
# 将字符串存储到链表中
head = ListNode(int(num[0]))
node = head
for i in num[1:]:
node.next = ListNode(int(i))
node = node.next
return head
# 链表表示的大整数加法
def add(num1, num2):
carry = 0
dummy = ListNode(0)
node = dummy
while num1 or num2 or carry:
val1 = num1.val if num1 else 0
val2 = num2.val if num2 else 0
carry, remainder = divmod(val1 + val2 + carry, 10)
node.next = ListNode(remainder)
node = node.next
num1 = num1.next if num1 else None
num2 = num2.next if num2 else None
return dummy.next
# 链表表示的大整数减法
def subtract(num1, num2):
# 先将链表翻转,实现低位对齐的减法
num1 = reverse(num1)
num2 = reverse(num2)
dummy = ListNode(0)
node = dummy
carry = 0
while num1 or num2:
val1 = num1.val if num1 else 0
val2 = num2.val if num2 else 0
diff = val1 - val2 - carry
if diff < 0:
carry = 1
diff += 10
else:
carry = 0
node.next = ListNode(diff)
node = node.next
num1 = num1.next if num1 else None
num2 = num2.next if num2 else None
# 去掉链表前面的0
result = reverse(dummy.next)
while result.next and result.val == 0:
result = result.next
return result
# 翻转链表,用于减法
def reverse(head):
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
# 打印链表表示的大整数
def print_num(head):
num = ""
while head:
num += str(head.val)
head = head.next
print(num)
# 主函数
def main():
num1 = generate_num()
print("num1: ", end="")
print_num(num1)
num2 = generate_num()
print("num2: ", end="")
print_num(num2)
result = add(num1, num2)
print("add: ", end="")
print_num(result)
result = subtract(num1, num2)
print("subtract: ", end="")
print_num(result)
if __name__ == "__main__":
main()
```
运行结果如下所示:
```
num1: 366012148584023809540912592887006693978829
num2: 43784148274628405696828022674879498694826723275849003
add: 43784148274628405696828022674879499020836985344769132
subtract: -43784148274628405696828022674879495074928831487618124
```
需要注意的是,减法得到的结果可能是负数,需要在打印时加上负号。另外,由于Python的int类型可以无限大,所以如果按照上面的实现方式直接进行加减法操作可能会出现错误。如果要针对Python的大整数进行加减法操作,需要对上面的代码做一些修改,比如将链表中存储的数字改为Python的int类型,然后直接进行加减法操作即可。
阅读全文