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.

Example

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

思路:首先确定加和的顺序,其次,考虑进位时,用上一位的余数给下一位加上,同时考虑二者一长一短的问题。


class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if(l1 == null || l2 == null){

            return null;

        }

        ListNode p3 = new ListNode(0);

        int value1 = 0, value2 = 0;

        ListNode result = p3;

        while(l1 != null && l2 != null){



            value2 = (l1.val + l2.val + value1) % 10;

            value1 = (l1.val + l2.val + value1) / 10;



            p3.next = new ListNode(value2);

            l1 = l1.next;

            l2 = l2.next;

            p3 = p3.next;



            if(l1 == null && l2 == null){

                break;

            }else if(l1 == null){

                l1 = new ListNode(0);

            }else if(l2 == null){

                l2 = new ListNode(0);

            }

        }

        if(value1 != 0){

            p3.next = new ListNode(value1);

        }

        return result.next;

    }

}

你可能感兴趣的:(2. Add Two Numbers)