LintCode-简单-链表求和

来源:互联网 发布:一流学科知乎 编辑:程序博客网 时间:2024/05/01 14:44

题目要求:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
遇到的问题:

  1. 两个参数给的链表需要逆序相加,得到的结果同样需要逆序存储,使用头插法可解决
  2. 测试时后面的数据非常大,在百亿以上,必须使用BigDecimal才能存放的下。

待解决问题
考虑一位一位的相加,这样没得到一位值直接保存在链表中即可,不用使用BigDecimal,也不需要多次的转型,估计效率会更高。但是如果两个数据长度不一样,在从个位开始加的时候需要考虑进位的问题,代码较麻烦,但如果使用的不是JAVA,没有BigDecimal类的话,实现起来就没这么简单了。此处待考虑!

public static ListNode addLists(ListNode l1, ListNode l2) {        // write your code here        String sumStr = sumLists(l1, l2);        System.out.println(sumStr);        ListNode head = new ListNode(-1);        head.next = null;        ListNode newNode;        for(int i=0; i<sumStr.length(); i++){            int x = Integer.parseInt(sumStr.substring(i, i + 1));            newNode = new ListNode(x);            newNode.next = head.next;            head.next = newNode;        }        return  head.next;    }    public static String sumLists(ListNode l1, ListNode l2){        StringBuffer sb1 = new StringBuffer();        StringBuffer sb2 = new StringBuffer();        while(l1 != null) {            sb1.append(l1.val);            l1 = l1.next;        }        while(l2 != null){            sb2.append(l2.val);            l2 = l2.next;        }        String str1 = sb1.toString();        String str2 = sb2.toString();        BigDecimal sum1 = new BigDecimal(0);        BigDecimal sum2 = new BigDecimal(0);        BigDecimal mutiNum = new BigDecimal(10);        for(int i=0; i<str1.length(); i++){            sum1 = sum1.multiply(mutiNum).add(new BigDecimal(Integer.parseInt(str1.charAt(str1.length() - 1 - i) + "")));        }        for(int i=0; i<str2.length(); i++){            sum2 = sum2.multiply(mutiNum).add(new BigDecimal(Integer.parseInt(str2.charAt(str2.length() - 1 - i) + "")));        }        return (sum1.add(sum2)).toString();    }
0 0
原创粉丝点击