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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

題目的意思是,輸入兩個ListNode l1和l2,每個ListNode表明一個‘反序’數字。例如4->3->2表明的是234。咱們的目的是求出兩個數字的加和,並以一樣的ListNode形式返回。假設每一個listnode都不會存在在首位的0,除非數字自己就是0.node

Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.git

想法

  • 這道題主要要求仍是熟悉ListNode的操做。
  • 還有兩個數字相加的問題都要考慮一個進位的問題。
  • 這道題因爲數字反序,因此實際上從首位開始相加正好符合咱們筆算的時候的順序。

解法

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;
        ListNode head = new ListNode(0);
        ListNode curr = head;
        int sum =0;
        
        while(p != null || q != null){
            sum = sum / 10;
            if(p != null){
                sum += p.val;
                p = p.next;
            }
            if(q != null){
                sum += q.val;
                q = q.next;
            }
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
        }
        if(sum >= 10){
            curr.next = new ListNode(1);
        }
        
        return head.next;
    }
相關文章
相關標籤/搜索