题目详情

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.

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

想法

  • 这道题主要要求还是熟悉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;
    }

soleil阿璐
350 声望45 粉丝

stay real ~