2. Add Two Numbers
Medium
59971568Share
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
错误解法
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
String s1 = "";
while(l1 != null){
int val = l1.val;
s1 = val + s1;
l1 = l1.next;
}
String s2 = "";
while(l2 != null){
int val = l2.val;
s2 = val + s2;
l2 = l2.next;
}
int result = Integer.parseInt(s1) + Integer.parseInt(s2);
if(result == 0){
return new ListNode(0);
}
ListNode head = new ListNode(1);
ListNode cur = head;
while(result != 0){
int temp = result % 10 ;
cur.next = new ListNode(temp);
cur = cur.next;
result /= 10;
}
return head.next;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null)
return null;
if(l1.val == 0 && l2.val == 0)
return new ListNode(0);
int n1 = 0;
int n2 = 0;
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
while(l1 != null){
list1.add(l1.val);
l1 = l1.next;
}
while(l2 != null){
list2.add(l2.val);
l2 = l2.next;
}
for(int i = list1.size() - 1; i >= 0; i--){
n1 = 10 * n1 + list1.get(i);
}
for(int i = list2.size() - 1; i >= 0; i--){
n2 = 10 * n2 + list2.get(i);
}
int ret = n1 + n2;
if(ret == 0)
return null;
ListNode head = new ListNode(1);
ListNode newHead = head;
while(ret > 0){
int d = ret % 10;
ret /= 10;
head.next = new ListNode(d);
head = head.next;
}
return newHead.next;
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YCvRIy2A-1580636266837)(pic/1580633840280.png)]
正确解法
不用转换,直接读取一个,计算一个
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cur = head;
int carry = 0;
while(l1 != null || l2 != null){
int x = (l1 != null) ? l1.val : 0;
int y = (l2 != null) ? l2.val : 0;
int sum = x + y + carry;
cur.next = new ListNode(sum % 10) ;
cur = cur.next;
carry = sum / 10;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if(carry > 0)
cur.next = new ListNode(carry);
return head.next;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)