用c++实现输入的两个超长整数都是非负整数,并且长度都小于100位。对于减法运算,如果运算结果为负数要在前面加上负号。并且运算结果要去掉前导0,例如运算结果如果是000123,要变成123输出。
时间: 2023-07-20 22:32:45 浏览: 75
好的,您的问题是如何用 C++ 实现两个超长非负整数的减法运算,并对结果进行处理以满足要求。
首先,我们可以把两个超长非负整数都转换成字符串,然后从字符串的末尾开始逐位相减,将结果保存到另一个字符串中。如果得到的结果是负数,则在字符串最前面添加负号,并将字符串中的负号删除。最后,还需要去掉字符串前面的所有零,并判断如果结果为空字符串,则说明运算结果为零。
以下是示例代码:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string subtract(string a, string b) {
string res = "";
int lena = a.length(), lenb = b.length();
int i = lena - 1, j = lenb - 1;
int borrow = 0;
while (i >= 0 || j >= 0) {
int x = i >= 0 ? a[i] - '0' : 0;
int y = j >= 0 ? b[j] - '0' : 0;
int z = x - y - borrow;
if (z < 0) {
z += 10;
borrow = 1;
} else {
borrow = 0;
}
res += (z + '0');
i--;
j--;
}
reverse(res.begin(), res.end());
// 删除前导0
while (res.length() > 1 && res[0] == '0') {
res.erase(0, 1);
}
// 判断结果是否为负数
if (borrow == 1) {
res.insert(0, "-");
}
return res;
}
int main() {
string a, b;
cin >> a >> b;
string res = subtract(a, b);
cout << res << endl;
return 0;
}
```
需要注意的是,该代码只能处理非负整数的减法运算,如果输入的有负数,需要另行处理。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)