对于20位以上的超长整数无法用int、long等基本类型表示,但可以考虑用字符串实现。本关任务:编写程序,基于字符串实现对超长整数的加法运算和减法运算,输入两个超长整数和运算符(+或-),输出运算结果。例如:输入123456789012345678901 + 123,输出123456789012345679024。要求:输入的两个超长整数都是非负整数,并且长度都小于100位。对于减法运算,如果运算结果为负数要在前面加上负号。并且运算结果要去掉前导0,例如运算结果如果是000123,要变成123输出。提示
时间: 2024-03-09 11:50:18 浏览: 19
好的,我会为你提供帮助。针对你的问题,我可以给出 Python 代码示例来实现对超长整数的加法和减法运算。
以下是加法运算的代码实现:
```python
num1 = input("请输入第一个数:")
num2 = input("请输入第二个数:")
# 对齐两个数
if len(num1) > len(num2):
num2 = num2.zfill(len(num1))
else:
num1 = num1.zfill(len(num2))
result = ""
carry = 0 # 进位
for i in range(len(num1)-1, -1, -1):
temp = int(num1[i]) + int(num2[i]) + carry
carry = temp // 10
result = str(temp % 10) + result
if carry:
result = str(carry) + result
print(result)
```
以下是减法运算的代码实现:
```python
num1 = input("请输入第一个数:")
num2 = input("请输入第二个数:")
# 对齐两个数
if len(num1) > len(num2):
num2 = num2.zfill(len(num1))
else:
num1 = num1.zfill(len(num2))
# 判断大小关系,确保 num1 >= num2
if num1 < num2:
num1, num2 = num2, num1
sign = "-"
else:
sign = ""
result = ""
borrow = 0 # 借位
for i in range(len(num1)-1, -1, -1):
temp = int(num1[i]) - int(num2[i]) - borrow
if temp < 0:
temp += 10
borrow = 1
else:
borrow = 0
result = str(temp) + result
# 去掉前导0
while result.startswith("0") and len(result) > 1:
result = result[1:]
print(sign + result)
```
上述代码中,我们首先对齐两个数,即在短的数前面补0,然后从低位到高位进行加减运算,同时考虑进位和借位。最后,我们需要去掉减法运算结果的前导0,并在需要的情况下在结果前面加上负号。
希望这些代码可以帮助你完成你的任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)