leetCode刷題記錄-2. 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.node

You may assume the two numbers do not contain any leading zero, except the number 0 itself.git

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

 

這道題其實就是利用鏈表來計算加法而已,每次都把sum/10來判斷是不是有超過10,其餘兩個數相加的時候,加上sum/10的值,跟日常計算加法的時候的思想同樣io

public class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        int sum = l1.val + l2.val;
        ListNode result = new ListNode(sum % 10);
        ListNode n1 = l1.next;
        ListNode n2 = l2.next;
        ListNode myNext = result;
        sum /= 10;
        while (n1 != null || n2 != null) {
            if (n1 != null) {
                sum += n1.val;
                n1 = n1.next;
            }
            if (n2 != null) {
                sum += n2.val;
                n2 = n2.next;
            }
            myNext.next = new ListNode(sum % 10);
            myNext = myNext.next;
            sum /= 10;
        }
        if (sum > 0) {
            myNext.next = new ListNode(sum);
        }
        return result;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
相關文章
相關標籤/搜索