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();
}
两个超级长的整数相加减
最新推荐文章于 2020-11-03 15:15:17 发布