题解 | #Powerful Calculator#

Powerful Calculator

https://www.nowcoder.com/practice/6bc1dd2ee0ce4257821531719b8d1c83

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool comp(vector<int>&A,vector<int>&B)
{
	if(A.size() != B.size()) return A.size() > B.size();
	
	for(int i = A.size() - 1;i >= 0;i--)
	{
		if(A[i] != B[i]) return A[i] > B[i];
	}
	return true;
}

vector<int>add(vector<int>A,vector<int>B)
{
	vector<int>ans;
	if(A.size() < B.size()) return add(B,A);
	int t = 0;
	for(int i = 0;i < A.size();i++)
	{
		t += A[i];
		if(i < B.size()) t += B[i];
		ans.push_back(t % 10);
		t /= 10;
	}
	if(t > 0) ans.push_back(t);
//	reverse(ans.begin(),ans.end());
	return ans;
}

vector<int>sub(vector<int>A,vector<int>B)
{
	vector<int>ans;
	int t = 0;
	for(int i = 0;i < A.size();i++)
	{
		t += A[i];
		if(i < B.size()) t -= B[i];
		if(t < 0){
			ans.push_back((t + 10) % 10);
			t = -1;
		}else{
			ans.push_back(t);
			t = 0;
		}
	}
	while(ans.size() > 1 && ans.back() == 0)ans.pop_back(); 
	reverse(ans.begin(),ans.end());
	return ans;
}

vector<int>mul_s(vector<int>A,int b)
{
	vector<int>ans;
	int t = 0;
	for(int i = 0;i < A.size();i++)
	{
		t = t + A[i] * b;
		ans.push_back(t % 10);
		t /= 10;
	}
	if(t > 0) ans.push_back(t);
	while(ans.size() > 1 && ans.back() == 0)ans.pop_back();
//	reverse(ans.begin(),ans.end());
	return ans; 
}

vector<int>mul(vector<int>&A,vector<int>&B)
{
	vector<int>ans;
	ans.push_back(0);
	for(int i = 0;i < B.size();i++)
	{
		vector<int>temp = mul_s(A,B[i]);
		reverse(temp.begin(),temp.end());
		for(int j = 0;j < i;j++) temp.push_back(0);
		reverse(temp.begin(),temp.end());
		ans = add(ans,temp);
	}
	while(ans.size() > 1 && ans.back() == 0)ans.pop_back();
	reverse(ans.begin(),ans.end());
	return ans;
}

int main(void)
{
	string s1,s2;
	cin >> s1 >> s2;
	vector<int>A,B;
	for(int i =s1.size() - 1;i >= 0;i--) A.push_back(s1[i] - '0');
	for(int i =s2.size() - 1;i >= 0;i--) B.push_back(s2[i] - '0');
	
	vector<int>add_res = add(A,B);
	reverse(add_res.begin(),add_res.end());
	for(auto a : add_res) cout << a;
	puts("");
	
	vector<int>sub_r;
	if(!comp(A,B)) {
		sub_r = sub(B,A);
		cout << "-";
	}else{
		sub_r = sub(A,B);
	}
	for(auto s : sub_r)cout << s;
	puts("");
	
	vector<int>mul_r = mul(A,B);
	for(auto n : mul_r)cout << n;
	
	return 0;
}

全部评论

相关推荐

09-29 17:44
已编辑
蔚来_测(准入职员工)
//鲨鱼辣椒:见不了了我实习了四个月上周再投筛选了一天就给我挂了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务