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


題目大意:兩個非負數分別逆序存放在兩個單鏈表中,將兩個單鏈表代表的數求和,並將和以單鏈表的形式返回。


解題思路:雙指針,先遍歷完較短的鏈表,將兩個鏈表對應節點值求和之後的值更新到較長的鏈表中,較短的鏈表遍歷完後再接着遍歷較長鏈表剩下的部分,此時僅以較長鏈表中節點的值作爲求和加數,但是要注意處理有進位的情況。


源代碼:(57 ms,beats 47.31%

/**
 * 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 lenth1 = 0, lenth2 = 0;
		ListNode p = l1, q = l2, result;
		int curRes;
		// 進位
		int carry = 0;
		while (p != null) {
			lenth1++;
			p = p.next;
		}
		while (q != null) {
			lenth2++;
			q = q.next;
		}
		if (lenth1 < lenth2) {
			result = l2;
			p = l1;
			q = l2;
		} else {
			result = l1;
			p = l2;
			q = l1;
		}
		ListNode preq = null;
		while (p != null) {
			curRes = p.val + q.val + carry;
			if (curRes >= 10) {
				carry = 1;
				curRes = curRes % 10;
			} else {
				carry = 0;
			}
			q.val = curRes;
			preq = q;
			p = p.next;
			q = q.next;
		}
		while (q != null) {
			curRes = q.val + carry;
			if (curRes >= 10) {
				carry = 1;
				curRes = curRes % 10;
			} else {
				carry = 0;
			}
			q.val = curRes;
			preq = q;
			q = q.next;
		}
		if (carry == 1) {
			preq.next = new ListNode(1);
		}
		return result;
    }
}


發佈了251 篇原創文章 · 獲贊 274 · 訪問量 73萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章