4月打卡活动第14天 LeetCode第445题:两数相加2(中等)
- 题目:给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
- 解题思路:链表转换为字符串计算。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
String ans1 = "";
String s1 = "";
String s2 = "";
String s11 = "";
String s22 = "";
while(l1.next != null){
s1 += l1.val;
l1 = l1.next;
}
s1 += l1.val;
for(int i=s1.length()-1;i>=0;i--){
s11 += s1.charAt(i);
}
while(l2.next != null){
s2 += l2.val;
l2 = l2.next;
}
s2 += l2.val;
for(int i=s2.length()-1;i>=0;i--){
s22 += s2.charAt(i);
}
int k = 0;
int t = 0;
int m = 0;
while(k<s1.length() && t<s2.length()){
int o = Integer.parseInt(""+s22.charAt(t++))+Integer.parseInt(s11.charAt(k++)+"");
ans1 += (m+o)%10;
m = (m+o)/10;
}
if(t==s2.length() && k<s1.length()){
while(k<s1.length()){
if(m==0){
ans1 += s11.charAt(k++);
}else{
int o = Integer.parseInt(s11.charAt(k++)+"");
ans1 += (m+o)%10;
m = (m+o)/10;
}
}
}else if(k==s1.length() && t<s2.length()){
while(t<s2.length()){
if(m==0){
ans1 += s22.charAt(t++);
}else{
int o = Integer.parseInt(s22.charAt(t++)+"");
ans1 += (m+o)%10;
m = (m+o)/10;
}
}
}
if(m==1) ans1 += 1;
ListNode ans = new ListNode(Integer.parseInt(""+ans1.charAt(ans1.length()-1)));
ListNode pre = ans;
for(int i=ans1.length()-2;i>=0;i--){
ListNode node = new ListNode(Integer.parseInt(""+ans1.charAt(i)));
pre.next = node;
pre = node;
}
return ans;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
while (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode head = null;
while (!stack1.isEmpty() || !stack2.isEmpty() || carry > 0) {
int sum = carry;
sum += stack1.isEmpty()? 0: stack1.pop();
sum += stack2.isEmpty()? 0: stack2.pop();
ListNode node = new ListNode(sum % 10);
node.next = head;
head = node;
carry = sum / 10;
}
return head;
}
}
作者:sweetiee
链接:https://leetcode-cn.com/problems/add-two-numbers-ii/solution/javakai-fa-by-sweetiee/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。