2. 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

链接: http://leetcode.com/problems/add-two-numbers/

题解:

单链表的操作,要注意链表为空时的判断。Time Complexity - O(n),Space Complexity - O(1)。

/**

 * Definition for singly-linked list.

 * public class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) {

 *         val = x;

 *         next = null;

 *     }

 * }

 */

public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if(l1 == null)

            return l2;

        if(l2 == null)

            return l1;

        ListNode result = new ListNode(-1);

        ListNode node = result;

        int carry = 0;

        

        while(l1 != null || l2 != null){

            int val1 = l1 == null ? 0 : l1.val;

            int val2 = l2 == null ? 0 : l2.val;

            node.next = new ListNode((val1 + val2 + carry) % 10);

            carry = val1 + val2 + carry >= 10 ? 1 : 0;

            if(l1 != null)

                l1 = l1.next;

            if(l2 != null)

                l2 = l2.next;

            node = node.next;

        }

        

        if(carry == 1)

            node.next = new ListNode(1);

        return result.next;

    }

}

Reference:

http://www.cnblogs.com/springfor/p/3864493.html

你可能感兴趣的:(number)