51nod 1005 大数加法

51nod
题目链接
注意
判断字符串的数值大小,先根据长度判断,当长度相等的时候再利用字符串的内置大于小于符号进行判断。
这道题坑挺多的,说好的大数加法,还顺带考了大数减法。
还有字符串的处理。
注意大数减法的时候,只用消除高位的0, 低位的0要保留。
但是也要注意结果刚好的0的情况,所以消除0后,最少保留一位。

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
bool flag = false;
string add(string s1, string s2){
	reverse(s1.begin(), s1.end());
	reverse(s2.begin(), s2.end());
	int lena = s1.size();
	int lenb = s2.size();
	int c = 0;
	string res;
	for(int i = 0; i < lena || i < lenb; i++){
		int t = 0;
		if(i < lena) t += s1[i] - '0';
		if(i < lenb) t += s2[i] - '0';
		res += to_string((t+c)%10);
		c = (t + c) / 10;
	}
	if(c != 0) res += "1";
	reverse(res.begin(), res.end());
	return res;
} 
bool cmp(string a, string b){ //a和b换不换 
	if(a.size() < b.size()) return true; //a的位数更短 则换 
	if(a.size() > b.size()) return false; //a的位数更长 不换 
	return a < b;
}
string sub(string s1, string s2){
	string res;
	bool tag = cmp(s1, s2);
	if(tag){
		swap(s1, s2);
		flag = true;
	}
	reverse(s1.begin(), s1.end());
	reverse(s2.begin(), s2.end());
	int lena = s1.size();
	int lenb = s2.size();
	
	
	int c = 0;
	for(int i = 0; i < lena || i < lenb; i++){
		int a = i < lena ? s1[i] - '0' + c: 0;
		int b = i < lenb ? s2[i] - '0' : 0;
		if(a < b){
			c = -1;
			res += to_string(a + 10 - b);
		}else{
			c = 0;
			res += to_string(a - b);
		}
	}
	int v = res.size() - 1;
	while(v > 0 && res[v]=='0') v--;
	res = res.substr(0, v + 1);
	reverse(res.begin(), res.end());
	return res;
}
int main(){
	string s1, s2, ans;
	//freopen("51nod_1005_17_in.txt","r",stdin); 
	cin >> s1 >> s2;
	if(s1[0] =='-' && s2[0]=='-'){
		s1 = s1.substr(1);
		s2 = s2.substr(1);
		ans = add(s1, s2);
		cout<<"-"<<ans<<endl;
	}else if(s1[0] != '-' && s2[0] != '-'){
		
		ans = add(s1, s2);
		cout<<ans<<endl;
	}else if(s1[0]=='-'){
		s1 = s1.substr(1);
		ans = sub(s2, s1);
		if(flag) cout<<'-';
		cout<<ans<<endl;
	}else{
		s2 = s2.substr(1);
		ans = sub(s1, s2);
		if(flag) cout<<'-';
		cout<<ans<<endl;
	}	
	
	
	return 0;
}

Java大数处理

import java.math.BigInteger;
import java.util.*;
public class Main{

	public static void main(String[] args) {
		Scanner in  = new Scanner(System.in);
		BigInteger a = in.nextBigInteger();
		BigInteger b = in.nextBigInteger();
		System.out.println(a.add(b));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值