现在的位置: 首页 > 综合 > 正文

Add Two Numbers

2014年09月05日 ⁄ 综合 ⁄ 共 945字 ⁄ 字号 评论关闭

You are given two linked lists representing two non-negative numbers. 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.

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;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
		if (l1 == null || l2 == null) return null;
		ListNode head = new ListNode(-1);
		ListNode cur = head;
		boolean carry = false;
		while (true) {
			int curval = l1.val + l2.val;
			if (carry == true)
				curval += 1;
			if (curval >= 10) {
				curval = curval % 10;
				carry = true;
			} else
				carry = false;
			cur.next = new ListNode(curval);
			cur = cur.next;
			if (l1.next == null && l2.next == null) break;
			// 保证两个链表的长度一样,若不一样,在短的那个前面补0
			l1 = (l1.next == null) ? new ListNode(0) : l1.next;
			l2 = (l2.next == null) ? new ListNode(0) : l2.next;
		}
		if (carry == true) {
			cur.next = new ListNode(1);
		}
		return head.next;
	}

}

抱歉!评论已关闭.