• List实现大整数减法


        @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;
        }
    
  • 相关阅读:
    [学习笔记]基于值域预处理的快速 GCD
    [学习笔记]整除偏序与zeta变换、Möbius变换、lcm卷积、gcd卷积
    [学习笔记]MinMax容斥
    [学习笔记]Pollard Rho算法
    [学习笔记]Miller Rabin测试
    [学习笔记]万能欧几里得
    用C#写程序安装包 Joe
    linux 命令
    几个有用的php字符串过滤,转换函数
    linux挂载 Windows分区
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286642.html
Copyright © 2020-2023  润新知