@Test
public void bigIntReduceTest(){
System.out.println(bigIntReduce("101312312735600","1323653943500"));
}
public String bigIntReduce(String num1,String num2){
List<String> strList1 = new LinkedList<>(Arrays.asList(num1.split("")));
List<String> strList2 = new LinkedList<>(Arrays.asList(num2.split("")));
List<Integer> list1 = new LinkedList<>();
List<Integer> list2 = new LinkedList<>();
CollectionUtils.collect(strList1, input -> Integer.valueOf(input.toString()),list1);
CollectionUtils.collect(strList2, input -> Integer.valueOf(input.toString()),list2);
Collections.reverse(list1);
Collections.reverse(list2);
return reduceList(list1,list2);
}
private String reduceList(List<Integer> list1,List<Integer> list2){
StringBuilder sb = new StringBuilder();
List<Integer> resList ;
//位数多的作为被减数
if (list1.size()>list2.size()){
resList = reduce(list1,list2);
}else {
resList = reduce(list2,list1);
//位数少的-位数多的加负号
sb.append("-");
}
//去除高位的0
for(int len=resList.size()-1,i=len;i>=0;i--) {
if (resList.get(i) == 0) {
resList.remove(i);
}else {
break;
}
}
//翻转
Collections.reverse(resList);
for (int aResList : resList) {
sb.append(aResList);
}
return sb.toString();
}
private List<Integer> reduce(List<Integer> list1,List<Integer> list2){
int len1 = list1.size();
int len2 = list2.size();
int len = len1>len2?len1:len2;
List<Integer> list3 = new LinkedList<>();
for(int i=0;i<len;i++) {
if (len2 > i) {
int res = list1.get(i) - list2.get(i);
if (res < 0) {
res += 10;
if (i + 1 < len1) {
list1.set(i + 1, list1.get(i + 1) - 1);
}
}
list3.add(res);
} else {
if(list1.get(i)<0){
list1.set(i, list1.get(i) + 10);
list1.set(i + 1, list1.get(i + 1) - 1);
}
list3.add(list1.get(i));
}
}
return list3;
}