LeetCode(Java) 两数相加
題目描述
給定兩個代表非負數的鏈表,數字在鏈表中是反向存儲的(鏈表頭結點處的數字是個位數,第二個結點上的數字是百位數…),求這個兩個數的和,結果也用鏈表表示。
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:243 + 564 = 807You 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
解題思路
(1)建立一個新的鏈表,用于存放結果;
(2)設立一個臨時變量 temp;
(3)把輸入的兩個鏈表從頭往后同時處理,每兩個對應位置相加,將結果存放于 temp;
(4)將 temp 對 10 取余,得到 temp 的個位數,存入鏈表中,并后移當前的鏈表節點;
(5)將 temp 對 10 求商,將結果作為進位的值(若大于10,則商為1,進位為1;若小于10,則商為0,不進位)。
注意:
(1)在循環的過程中,需要考慮兩個鏈表不等長的情況。
(2)需要考慮當兩個鏈表都遍歷到底(即都 == null),但若 temp = 1,即還需進位,則需要在進行一個循環,將 temp 的進位數加入鏈表末端。
代碼實現
/*** 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) {if (l1 == null) {return l2;}if (l2 == null) {return l1;}ListNode res = new ListNode(-1);ListNode cur = res;int temp = 0;while (l1 != null || l2 != null || temp != 0) {if (l1 != null) {temp += l1.val;l1 = l1.next;}if (l2 != null) {temp += l2.val;l2 = l2.next;}cur.next = new ListNode(temp % 10);cur = cur.next;temp = temp / 10;}return res.next;} }總結
以上是生活随笔為你收集整理的LeetCode(Java) 两数相加的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer(Java实现) 顺时针打
- 下一篇: 同步、异步、阻塞、非阻塞、BIO、NIO