2. Add Two Numbers

2016-10-07  本文已影响0人  FlynnLWang

Question Description

Screenshot 2016-10-06 21.16.19.png

My Code

/**
 * 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) {
        int first = l1.val + l2.val;
        ListNode root = new ListNode(first % 10);
        ListNode head = root;
        int carry = first / 10;
        boolean flag = true;
        l1 = l1.next;
        l2 = l2.next;
        while (flag) {
            if (l1 == null && l2 == null && carry == 0) {
                flag = false;
                break;
            }
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;
            int val = v1 + v2 + carry;
            ListNode next = new ListNode(0);
            if (val >= 10) {
                next.val = val - 10;
                carry = 1;
            } else {
                next.val = val;
                carry = 0;
            }
            l1 = l1 == null ? l1 : l1.next;
            l2 = l2 == null ? l2 : l2.next;
            root.next = next;
            root = root.next;
        }
        return head;
    }
}

Test Result

Screenshot 2016-10-06 21.15.55.png

Solution

Very common question. Just calculate each value, if result is greater than 10, get the remainder and pass the carry to the next number pair.

上一篇下一篇

猜你喜欢

热点阅读