Problem
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { l1 = reverse(l1); l2 = reverse(l2); //add ListNode dummy = new ListNode(0), l3 = dummy; int carry = 0; while (l1 != null || l2 != null) { int sum = carry; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } l3.next = new ListNode(sum%10); l3 = l3.next; carry = sum/10; } if (carry != 0) l3.next = new ListNode(carry); return reverse(dummy.next); } private ListNode reverse(ListNode head) { ListNode pre = null; while (head != null) { ListNode next = head.next; head.next = pre; pre = head; head = next; } return pre; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/72591.html
摘要:題目要求對以鏈表形式的兩個整數(shù)進(jìn)行累加計算。思路一鏈表轉(zhuǎn)置鏈表形式跟非鏈表形式的最大區(qū)別在于我們無法根據(jù)下標(biāo)來訪問對應(yīng)下標(biāo)的元素。因此這里通過先將鏈表轉(zhuǎn)置,再從左往右對每一位求和來進(jìn)行累加。通過??梢詫崿F(xiàn)先進(jìn)后出,即讀取順序的轉(zhuǎn)置。 題目要求 You are given two non-empty linked lists representing two non-negative i...
摘要:公眾號愛寫給定一個已按照升序排列的有序數(shù)組,找到兩個數(shù)使得它們相加之和等于目標(biāo)數(shù)。函數(shù)應(yīng)該返回這兩個下標(biāo)值和,其中必須小于。示例輸入輸出解釋與之和等于目標(biāo)數(shù)。 公眾號: 愛寫bug(ID:icodebugs) 給定一個已按照升序排列 的有序數(shù)組,找到兩個數(shù)使得它們相加之和等于目標(biāo)數(shù)。 函數(shù)應(yīng)該返回這兩個下標(biāo)值 index1 和 index2,其中 index1 必須小于 index2。...
摘要:公眾號愛寫給定一個已按照升序排列的有序數(shù)組,找到兩個數(shù)使得它們相加之和等于目標(biāo)數(shù)。函數(shù)應(yīng)該返回這兩個下標(biāo)值和,其中必須小于。示例輸入輸出解釋與之和等于目標(biāo)數(shù)。 公眾號: 愛寫bug(ID:icodebugs) 給定一個已按照升序排列 的有序數(shù)組,找到兩個數(shù)使得它們相加之和等于目標(biāo)數(shù)。 函數(shù)應(yīng)該返回這兩個下標(biāo)值 index1 和 index2,其中 index1 必須小于 index2。...
摘要:同時題目假設(shè)每組輸入恰好只有一個答案,并且不能重復(fù)使用同一元素。理解這道題是可以用兩層循環(huán)蠻力解決的,但是效率太低了。如果這兩個元素和大于目標(biāo)數(shù)組,指針左移如果小于,指針右移。如果等于,則返回這兩個元素的位置記得用數(shù)組的數(shù)值加一解法 題目詳情 Given an array of integers that is already sorted in ascending order, fi...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖恪K栽谶@里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個索引嘻嘻。 順序整理 1~50 1...
閱讀 688·2021-11-22 15:32
閱讀 2778·2021-11-19 09:40
閱讀 2393·2021-11-17 09:33
閱讀 1344·2021-11-15 11:36
閱讀 1933·2021-10-11 10:59
閱讀 1540·2019-08-29 16:41
閱讀 1839·2019-08-29 13:45
閱讀 2220·2019-08-26 13:36