【leetcode】2.Add Two Numbers

来源:互联网 发布:淘宝上拍卖的房子 编辑:程序博客网 时间:2024/06/05 20:29

题目

You are given two linked lists representing two non-negative numbers. 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.

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

/** * 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) {    }}题意:   }

}
题意:
说是有两个链表,每个节点都是0-9的非负数。但是这数呢,他是逆序的,也就是这2->4->3,实际上代表的是342
两链表各个位按照十进制相加,求一数。

解题:

官方答案:

https://leetcode.com/articles/add-two-numbers/
感悟:
题目很简单但是应该关注一下官方答案的思考逻辑

        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;        }

问题:官方答案是不是重复考虑了p是否==null这个问题?

递归解法

0 0