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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


很绝望,又差点没有看懂题目,我恨英语。。。

2.Add Two Numbers_第1张图片

先来我拙劣的思路:

1.新链表存储结果。
2.需要一个变量存储进位的值。
3.循环链表,结束条件是:俩链表里的数都没了,也没有进位值。

来一个我冗长的代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode index=result;
        int carryBit = 0;
        if(l1 != null||l2 != null){
            while(l1 != null||l2 != null||carryBit!=0){
                ListNode newNode = new ListNode(0);
                int newNum=(l1==null?0:l1.val)+(l2==null?0:l2.val)+carryBit;
                carryBit=newNum/10;
                newNum=newNum%10;
                newNode.val=newNum;
                if(l1!=null){
                    l1=l1.next;
                }
                if(l2!=null){
                    l2=l2.next;
                }
                
                index.next=newNode;
                index=newNode;
            }
        }
        return result.next;
    }
}

看的时候发现一个更简洁的:

  //Easiest solution, memory limit exceeded.
        
        ListNode current = head;
        while(l1 != null || l2 != null){
            sum = l1.val + l2.val + carry;
            current.val = sum % 10;
            carry = sum / 10;
            
            if(l1.next != null || l2.next != null || carry != 0){
                ListNode newNode = new ListNode(0);
                current.next = newNode;
                current = current.next;
            }
            
        }

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