两个超级长的整数相加减

public static void main(String[] args) {
		String b = "21342687631748172482311832418324";
		String a = "4389265786296528365286523856385";
		List<Integer> aList = getIntList(a);
		List<Integer> bList = getIntList(b);
		add(aList, bList);
		sub(aList, bList);
	}

	public static List<Integer> getIntList(String str) {
		List<Integer> intList = new ArrayList<>();
		for (char s : str.toCharArray()) {
			intList.add(Integer.parseInt(String.valueOf(s)));
		}
		return intList;
	}

	public static String add(List<Integer> aList, List<Integer> bList) {
		int alength = aList.size() - 1;
		int blength = bList.size() - 1;
		int carryBit = 0;
		StringBuffer sb = new StringBuffer();
		while (alength >= 0 || blength >= 0) {
			int tmp = 0;
			if (alength >= 0 && blength >= 0) {
				tmp = aList.get(alength) + bList.get(blength) + carryBit;
			} else if (alength >= 0) {
				tmp = aList.get(alength) + carryBit;
			} else if (blength >= 0) {
				tmp = bList.get(blength) + carryBit;
			}
			sb.append(tmp % 10 + "");
			carryBit = tmp / 10;// 只有两个数相加只会是0或1
			alength--;
			blength--;
		}
		sb.append(carryBit + "");
		return getResultString(sb.reverse());
	}

	public static String sub(List<Integer> aList, List<Integer> bList) {
		StringBuffer sb = new StringBuffer();
		boolean minus = false;
		if (aList.size() < bList.size()) {
			List<Integer> tmpList = new ArrayList<>();
			tmpList.addAll(aList);
			aList.removeAll(tmpList);
			aList.addAll(bList);
			bList.removeAll(aList);
			bList.addAll(tmpList);
			minus = true;
		}
		int alength = aList.size() - 1;
		int blength = bList.size() - 1;
		int borrow = 0;

		while (alength >= 0) {
			int tmp = 0;
			if (alength >= 0 && blength >= 0) {
				if (aList.get(alength) > bList.get(blength)) {
					tmp = aList.get(alength) - borrow - bList.get(blength);
				} else {
					tmp = aList.get(alength) - borrow + 10 - bList.get(blength);
					borrow = 1;
				}

			} else if (alength >= 0) {
				if (aList.get(alength) == 0 && borrow != 0) {
					tmp = aList.get(alength) + 10 - borrow;
				} else {
					tmp = aList.get(alength) - borrow;
					borrow = 0;
				}
			}
			sb.append(tmp + "");
			alength--;
			blength--;
		}
		if (minus) {
			sb.append("-");
		}
		return getResultString(sb.reverse());
	}

	public static String getResultString(StringBuffer sb) {
		while (sb.length() > 1 && sb.charAt(0) == '0') {
			sb.deleteCharAt(0);
		}
		System.err.println(sb.toString());
		return sb.toString();

	}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值