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;
    }
相关文章
相关标签/搜索