Add Two Numbers (leetcode2)

来源:互联网 发布:百度贴吧和天涯知乎 编辑:程序博客网 时间:2024/06/09 18:19

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8 


基本思路:首先想到将逆序存储的链结点转换为正确的整数,然后相加得到结果,再逆序存储回链表中去,因为考虑到数值非常的大,所以要使用到大数类,做出来的效率也比较慢,代码如下:

import java.math.BigInteger;class ListNode {     int val;     ListNode next;     ListNode(int x) { val = x; }     public String toString(){     return val+"";     }}public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        BigInteger sum1 = BigInteger.ZERO;        BigInteger sum2 = BigInteger.ZERO;        ListNode current = l1;        int power = 0;        //转换成整数1        while(current!=null){        sum1 = sum1.add(new BigInteger(current.val+"").multiply(new BigInteger("10").pow(power++)));        current = current.next;        }        current = l2;        power = 0;        //转换成整数2        while(current!=null){        sum2 = sum2.add(new BigInteger(current.val+"").multiply(new BigInteger("10").pow(power++)));        current = current.next;        }        //得到答案整数        BigInteger sum = sum1.add(sum2);        String str = sum.toString();        //存储回链表中        ListNode answer = new ListNode(Integer.valueOf(str.charAt(str.length()-1)+""));        current = answer;        for(int i=str.length()-2;i>=0;i--){        current.next = new ListNode(Integer.valueOf(str.charAt(i)+""));        current = current.next;        }        return answer;            }}

参考了discuss,得到了一个新的思路,就是每次对两个链表的一位数字(即一个链结点)进行相加,再考虑到是否需要进位的情况,就能很容易得到答案,代码如下:

public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = 0; ListNode answer = new ListNode(0); ListNode current = answer; while (l1 != null || l2 != null || sum != 0) {        if (l1 != null) {            sum += l1.val;            l1 = l1.next;        }        if (l2 != null) {            sum += l2.val;            l2 = l2.next;        }        current.next = new ListNode(sum%10);        sum /= 10;        current = answer.next;    } return answer.next;  }}


              

原创粉丝点击