【Shawn-LeetCode】2.Add Two Numbers

来源:互联网 发布:做网络直播需要什么设备 编辑:程序博客网 时间:2024/05/23 01:18

2.Add Two Numbers

Question:

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

Subscribe to see which companies asked this question.

解析:

如果使用C语言做的话,可以用next指针进行处理,效率确实会高,Java理解起来就有点困难了。首先明确这种题用递归无疑是最快的,建立临时结构体curr来保存和的个位,curr的next指向下一位,并把进位传递过去,并不一定要向题目中说的要进行倒置保存。

第二点要考虑情况,l1比l2长,相等,短三种情况,长或者短,为其中一个添加一个新的节点,并参与运算,如果相等,则判断进位是否为空,为空则结束,不为空则将进位置为第一位,以下为源代码:


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        return helper(l1,l2,0);    }    public ListNode helper(ListNode l1, ListNode l2, int carry){        if(l1==null && l2==null){            return carry == 0? null : new ListNode(carry);        }        if(l1==null && l2!=null){            l1 = new ListNode(0);        }        if(l2==null && l1!=null){            l2 = new ListNode(0);        }        int sum = l1.val + l2.val + carry;        ListNode curr = new ListNode(sum % 10);        curr.next = helper(l1.next, l2.next, sum / 10);        return curr;    }}