大整数相加

记录一道手撕代码的面试题

	大整数相加可以用BigInteger解决。(但是面试肯定不会让你用这个)
	//BigInteger类解决(可用于对后续代码结果的测试)
public static void main(String[] args) {
		String s1 = "11567890087657890876";
		String s2 = "19133324567865654123234";
		BigInteger num1 = new BigInteger(s1);
		BigInteger num2 = new BigInteger(s2);
		BigInteger num3 = num1.add(num2);
		System.out.println(num3);
}

//一般解法:
public static void main(String[] args) {
		//大整数相加
		String s1 = "11567890087657890876";
		String s2 = "19133324567865654123234";
		char[] num1 = new StringBuffer(s1).reverse().toString().toCharArray();
		char[] num2 = new StringBuffer(s2).reverse().toString().toCharArray();
		StringBuilder result = new StringBuilder();
		int carry = 0;
		int maxIndex1 = Math.min(num1.length, num2.length);
		int maxIndex2 = Math.max(num1.length, num2.length);
		//处理长度一致的部分
		for(int i = 0;i<maxIndex1;i++){
			int temp = (num1[i]-'0')+(num2[i]-'0')+carry;//利用ASCII码的特点进行按位相加运算
			result.append(temp%10);
			carry = temp/10;
		}
		//处理多余长度部分
		//没有进位直接拼接剩余部分
		if(carry==0){
			for(int i = maxIndex1;i<maxIndex2;i++){
				if(num1.length>num2.length){
					result.append(num1[i]);
				}else{
					result.append(num2[i]);
				}
			}
		}else{//有进位要用剩余部分再次和进位相加
			for(int i = maxIndex1;i<maxIndex2;i++){
				if(num1.length>num2.length){
					int temp = (num1[i]-'0')+carry;
					result.append(temp%10);
					carry = temp/10;
				}else{
					int temp = (num2[i]-'0')+carry;
					result.append(temp%10);
					carry = temp/10;
				}
			}
		}
		System.out.println(result.reverse().toString());
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值