[Leetcode]2. Add Two Numbers

来源:互联网 发布:淘宝查询别人购买记录 编辑:程序博客网 时间:2024/06/05 14:32

https://leetcode.com/problems/add-two-numbers/

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


题目翻译:

输入2个无序非空链表,所包含的元素值都为非负整数。 请将这2个链表中的每一项两两相加填充至链表并返回。


条件:

1. 链表的元素是十进制的,相加大于等于10,则去掉十位数,并进到下一位

2. 如果2个链表长度可能不一,这点和1.都需要同时考虑。例如输入是[2,9]和[9],则返回需要是[1,0,1]


解题:

可以考虑使用递归破解,但要注意判断条件。(感觉我写的有点乱(烂))

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {            // 判断是否需要进位            int carryToNext = 0;            if ((l1.val + l2.val) >= 10) {                carryToNext = 1;            }            System.out.println("l1.val:" + l1.val + ", l2.val:" + l2.val + ", carryToNext:" + carryToNext);            //这一轮的值            ListNode ln = new ListNode((l1.val + l2.val) % 10);            //如果2个链表都还有next,则递归进入下一轮            if ((l1.next != null) && (l2.next != null)) {                // 将进位写入l2.next中(不会改变原链表中的值)                l2.next.val += carryToNext;                ln.next = addTwoNumbers(l1.next, l2.next);                // 进位已经被处理,清空                carryToNext = 0;            } else if ((l1.next != null) || (l2.next != null)) { // 只有其中一个链表还有next值,继续递归处理,同时传入进位数据                ln.next = addTwoNumbers(((l1.next != null) ? l1.next : l2.next), new ListNode(carryToNext));                // 进位已经被处理,清空                carryToNext = 0;            }            // 2个链表都已经没有next,但本轮产生了进位,则加在结尾处。            if (carryToNext > 0) {                ln.next = new ListNode(1);            }            return ln;        }



标准答案很巧妙,直接一个循环搞定,膜拜一下。。

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {    ListNode dummyHead = new ListNode(0);    ListNode p = l1, q = l2, curr = dummyHead;    int carry = 0;    while (p != null || q != null) {        int x = (p != null) ? p.val : 0;        int y = (q != null) ? q.val : 0;        int sum = carry + x + y;        carry = sum / 10;        curr.next = new ListNode(sum % 10);        curr = curr.next;        if (p != null) p = p.next;        if (q != null) q = q.next;    }    if (carry > 0) {        curr.next = new ListNode(carry);    }    return dummyHead.next;}


                                             
0 0
原创粉丝点击