大整数减法

#include <iostream>
#include <string>
#include <deque>
using std::cout;
using std::endl;
using std::string;
using std::deque;

class Solution
{
	public:
		string bigNumSub(const string & a,const string & b){
			//--------------------
			//a,b格式:
			//1)a,b非空且都是数字字符
			//2)a,b不带正负符号
			//3)a,b没有前导0
			//如2342332,23300,0合法
			//+2322,-23423,0243不合法
			//由调用函数保证a,b的格式
			//--------------------
			//num1存放绝对值较大的数
			string num1 = a,num2 = b;
			string sign = "";//结果是否是负数
			if(!isGE(num1,num2)){
				num1.swap(num2);
				sign = "-";
			}
			int n1 = num1.size();
			int n2 = num2.size();
			deque<char> result(n1,0);//存放相减的结果
			char carry = 0;//借位
			int k = n1 - 1;
			//处理重叠部分
			for(int i = n1-1,j = n2 - 1;j >= 0;--i,--j,--k){
				result[k] = carry + num1[i] - num2[j];
				carry = 0;
				while(result[k] < 0){
					result[k] += 10;
					carry -= 1;//向高位的借位
				}
			}
			//处理num1剩余的部分
			while(k >= 0 ){
				result[k] = carry + num1[k] - '0';
				carry = 0;
				while(result[k] < 0){
					result[k] += 10;
					carry -= 1;//向高位的借位
				}
				--k;
			}
			//找到非0的最高位
			int first = 0;
			while(first < n1 && result[first] == 0){
				++first;
			}
			//将result的结果转换成string返回
			string resultStr;
			if(first == n1){
				resultStr = "0";
			}else{
				resultStr = string(n1-first,'0');
				int i = 0;
				while(first < n1){
					resultStr[i] += result[first];
					++i;
					++first;
				}
			}
			return sign + resultStr;
		}
	private:
		//判断a是否 >= b
		bool isGE(const string & a,const string & b){
			if(a.size() != b.size()){
				return a.size() > b.size();
			}
			return a >= b;
		}
};

int main(){
	Solution sl;
	string a = "987654321";
	string b = "0";
	cout << sl.bigNumSub(a,b) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/creativele/article/details/81739525