LeetCode 解题报告 - 2. Add Two Numbe

2016-10-09  本文已影响0人  秋名山菜车手

从今天开始,写一下我在刷 LeetCode 时的心得体会,包括自己的思路和别人的优秀思路,欢迎各种监督啊! 2016/10/9
编程语言是 Java,代码托管在我的 GitHub 上,包括测试用例。欢迎各种批评指正!

<br />

题目 —— Add Two Numbers

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
<br >

解答

/**
 * 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) {
        ListNode prev = new ListNode(0);
        ListNode tmp = prev;
        int carry = 0;
        int sum = 0;
        
        while (l1 != null || l2 != null || carry != 0) {
            sum = ((l1 == null) ? 0 : l1.val) + ((l2 == null) ? 0 : l2.val) + carry;
            carry = sum / 10;
            sum %= 10;
            tmp.next = new ListNode(sum);
            
            l1 = (l1 == null) ? l1 : l1.next;
            l2 = (l2 == null) ? l2 : l2.next;
            tmp = tmp.next;
        }
        return prev.next;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读