对于20位以上的超长整数无法用int、long等基本类型表示,但可以考虑用字符串实现。 本关任务:编写程序,基于字符串实现对超长整数的加法运算和减法运算,输入两个超长整数和运算符(+或-),输出运算结果。 例如:输入123456789012345678901 + 123,输出123456789012345679024。 要求:输入的两个超长整数都是非负整数,并且长度都小于100位。对于减法运算,如果运算结果为负数要在前面加上负号。并且运算结果要去掉前导0,例如运算结果如果是000123,要变成123输出。 提示 对于加法,考虑先把两个数对齐,再按位加(要考虑进位),运算结果以字符串形式输出。 对于减法,先比较被减数和减数的大小,如果被减数小于减数,则需要交换被减数和减数,然后再按位减(要考虑借位)。
时间: 2024-03-14 16:44:12 浏览: 17
好的,下面是我为您编写的 Python 代码,实现超长整数的加减运算:
```python
def add(a, b):
# 将两个字符串补齐到相同长度
len_a, len_b = len(a), len(b)
if len_a > len_b:
b = '0' * (len_a - len_b) + b
else:
a = '0' * (len_b - len_a) + a
carry = 0 # 进位
res = '' # 存放结果
for i in range(max(len_a, len_b) - 1, -1, -1):
tmp = int(a[i]) + int(b[i]) + carry
res = str(tmp % 10) + res
carry = tmp // 10
if carry:
res = '1' + res
return res
def sub(a, b):
# 判断 a 是否小于 b
if a < b:
a, b = b, a
is_negative = True
else:
is_negative = False
# 将两个字符串补齐到相同长度
len_a, len_b = len(a), len(b)
b = '0' * (len_a - len_b) + b
borrow = 0 # 借位
res = '' # 存放结果
for i in range(len_a - 1, -1, -1):
tmp = int(a[i]) - int(b[i]) - borrow
if tmp < 0:
tmp += 10
borrow = 1
else:
borrow = 0
res = str(tmp) + res
# 去掉前导0
while res.startswith('0') and len(res) > 1:
res = res[1:]
if is_negative:
res = '-' + res
return res
# 主函数
if __name__ == '__main__':
a, op, b = input().split()
if op == '+':
print(add(a, b))
elif op == '-':
print(sub(a, b))
```
这段代码实现了超长整数的加减运算。其中 `add` 函数实现了加法,`sub` 函数实现了减法。主函数中首先读入两个超长整数和运算符,然后根据运算符调用相应的函数计算结果,并输出。
注意,这段代码中使用了 Python 的字符串操作,可以方便地处理超长整数。具体来说,为了实现对齐和补齐,我们可以使用字符串的乘法和加法运算;而在按位加减的过程中,则可以直接将字符串转换成整数处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)