2. Add Two Numbers

题目

原始地址 :https://leetcode.com/problems/add-two-numbers/#/description

/**
 * 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) {
        
    }
}

描述

给定两个非负整数,它们的数字反向保存在两个链表中。求两个数字的和并以链表的形式返回。

分析

题目比较简单,类似竖式的加法,由低位到高位依次相加即可。注意终止条件、空指针判断和进位。

解答

/**
 * 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 carry = 0, v1, v2, sum;
        ListNode head = new ListNode(0), node = head;
        while (l1 != null || l2 != null || carry != 0) {
            v1 = l1 == null ? 0 : l1.val;
            v2 = l2 == null ? 0 : l2.val;
            sum = v1 + v2 + carry;
            ListNode n = new ListNode(sum % 10);
            node.next = n;
            node = n;
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return head.next;
    }
}
posted @ 2017-04-26 17:42  北冥尝有鱼  阅读(105)  评论(0编辑  收藏  举报