Amazon Tag

Add Two Numbersjava

  • 問題: 給出兩個鏈表分別表示倒序的非負整數,求兩個整數的和
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        int carry = 0;
        ListNode curr = new ListNode(0);
        ListNode dummy = curr;
        while (l1 != null && l2 != null) {
            curr.next = new ListNode((l1.val + l2.val + carry) % 10);
            carry = (l1.val + l2.val + carry) / 10;
            curr = curr.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 == null && l2 != null) {
            curr.next = new ListNode((l2.val + carry) % 10);
            carry = (l2.val + carry) / 10;
            curr = curr.next;
            l2 = l2.next;
        }
        while (l2 == null && l1 != null) {
            curr.next = new ListNode((l1.val + carry) % 10);
            carry = (l1.val + carry) / 10;
            curr = curr.next;
            l1 = l1.next;
        }
        if (carry != 0) {
            curr.next = new ListNode(carry);
        }
        
        return dummy.next;
    }
}
複製代碼
//優化while循環
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        int carry = 0;
        ListNode head = new ListNode(0);
        ListNode dummy = head;
        while (l1 != null || l2 != null) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            head.next = new ListNode(sum % 10);
            head = head.next;
            carry = sum / 10;
        }
        if (carry != 0) {
            head.next = new ListNode(carry);   
        }
        
        return dummy.next;
    }
}
複製代碼

445. Add Two Numbers II優化

  • 問題: 給出兩個鏈表分別表示正序的非負整數,求兩個整數的和
  • 思路: 先reverse而後再直接求加 -> 長度不等的時候, 須要考慮進位匹配問題 —> 計算長度用0補位 或者是先將長的跳過 從同一塊兒點開始reverse, 高位是在前面,計算完了還要reverse回去
相關文章
相關標籤/搜索