您的位置 首页 JAVA(2017)

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.

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

 

/**
 * 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) {
        int extra = 0;
        ListNode curr1 = l1;
        ListNode curr2 = l2;
        ListNode res = new ListNode(0);
        ListNode ress = res;
        while(curr1 != null || curr2 != null){
            if(curr1 == null){
                ress.next = curr2;
                int tmp = curr2.val + extra;
                extra = 0;
                if(tmp >= 10){
                    tmp = tmp -10;
                    extra = 1;
                }                
                ress.next.val = tmp;
                ress = ress.next;
                curr2 = curr2.next;
                continue;
            }
            if(curr2 == null){
                ress.next = curr1;
                int tmp = curr1.val + extra;
                extra = 0;
                if(tmp >= 10){
                    tmp = tmp -10;
                    extra = 1;
                }                
                ress.next.val = tmp;
                ress = ress.next;
                curr1 = curr1.next;
                continue;
            }
            int tmp = curr1.val +curr2.val + extra;
            extra = 0;
            if(tmp >= 10){
                tmp = tmp -10;
                extra = 1;
            }
            ress.next = curr1;
            ress.next.val = tmp;
            ress = ress.next;
            curr2 = curr2.next;
            curr1 = curr1.next;
        }
        if(extra ==1){
            ListNode extranode = new ListNode(extra);
            ress.next = extranode;
            ress = ress.next;
        }
        ress.next = null;
        return res.next;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 2. Add Two Numbers》

发表评论

邮箱地址不会被公开。

返回顶部