大数运算之大数减法
模拟减法思想:借位
class Solution {
public:
string subtraction(string a, string b) {
int ans;//当ans为1表示结果为非负数,当ans为0表示结果为负数
//判断a,b大小
if(a.size()>b.size())
{
ans = 1;
}
else if(a.size() == b.size())
{
if(a>=b)
ans = 1;
else
ans = 0;
}
else
ans = 0;
//假设a>=b,当a<b时,交换a,b
if(ans==0)
a.swap(b);
string str;
int carry = 0;//借位项
for(int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; --i, --j) {
int x = i < 0 ? 0 : a[i] - '0' -carry;
int y = j < 0 ? 0 : b[j] - '0';
if(x<y)
carry = 1;
else
carry = 0;
int sum = (x+10*carry-y);
str.insert(0,1,sum+'0');
}
//如果最高位为0,则删除该项
if(str[0]=='0')
str.erase(0,1);
if(ans==0)
str.insert(0,1,'-');//结果为负数,符号位为-
return str;
}
};