2. 兩數(shù)相加
難度中等5459
給你兩個 非空 的鏈表介褥,表示兩個非負的整數(shù)妻顶。它們每位數(shù)字都是按照 逆序 的方式存儲的替梨,并且每個節(jié)點只能存儲 一位 數(shù)字。
請你將兩個數(shù)相加拔妥,并以相同形式返回一個表示和的鏈表。
你可以假設除了數(shù)字 0 之外,這兩個數(shù)都不會以 0 開頭许帐。
示例 1:
image
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.
示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]
示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]
提示:
- 每個鏈表中的節(jié)點數(shù)在范圍
[1, 100]
內(nèi) 0 <= Node.val <= 9
- 題目數(shù)據(jù)保證列表表示的數(shù)字不含前導零
My solution
import java.math.BigInteger;
public class Solution {
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
StringBuffer str1= new StringBuffer();
StringBuffer str2= new StringBuffer();
while(l1!=null){
str1.append(l1.val);
l1=l1.next;
}
while(l2!=null){
str2.append(l2.val);
l2=l2.next;
}
String str1s =str1.reverse().toString();
String str2s =str2.reverse().toString();
String str = String.valueOf(new BigInteger(str1s).add(new BigInteger(str2s)));
int[] tmp=new int[str.length()];
for(int i=0;i<str.length();i++){
tmp[i]=Integer.parseInt(String.valueOf(str.charAt(i)));
}
ListNode l3=new ListNode(tmp[str.length()-1]);
ListNode temp=l3;
for(int i=str.length()-2;i>=0;i--) {
temp.next = new ListNode(tmp[i]);
temp = temp.next;
}
return l3;
}
}
執(zhí)行用時:12 ms, 在所有 Java 提交中擊敗了22.19%的用戶
內(nèi)存消耗:38.9 MB, 在所有 Java 提交中擊敗了43.66%的用戶
時間復雜度O(n)
空間復雜度O(n)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode pre = new ListNode(0);
ListNode cur = pre;
int carry = 0;
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(carry == 1) {
cur.next = new ListNode(carry);
}
return pre.next;
}
}
以上是另一種方法,更加簡單毕谴,其中有可改進的地方成畦,把carry=sum/10改為carry=sum>9?1:0,因為carry最大只能是1涝开,不可能出現(xiàn)兩個個位數(shù)相加達到二十及以上的情況(即使加上進位carry循帐,因為carry從開始 最大就是1)
作者:guanpengchn
鏈接:https://leetcode-cn.com/problems/add-two-numbers/solution/hua-jie-suan-fa-2-liang-shu-xiang-jia-by-guanpengc/