描述
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.思路
使用int类型的加法实现,先转成加法再进行分割成链表
/**
* 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) {
int i1 = 0, i2 = 0, i3 = 0, base = 1;
ListNode temp = l1;
while(temp!=null){
i1 = i1 + temp.val*base;
temp = temp.next;
base = base * 10;
}
temp = l2;
base = 1;
while(temp!=null){
i2 = i2 + temp.val*base;
temp = temp.next;
base = base * 10;
}
i3 = i1 + i2;
String out = Integer.toString(i3);
temp = null;
for(int i = 0 ;i <out.length();i++){
int num = (int)out.charAt(i) - (int)('0');
ListNode newNode = new ListNode(num);
newNode.next = temp;
temp = newNode;
}
return temp;
}
}结果发生了溢出
变换思路
使用按位相加、进位的方法生成链表
一开始想着进位,忽视进位的情况不止一种,改为用int进行存储,还能累加进位。
使用两个指针保证从链表头进行输出。
/**
* 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 head = new ListNode(0);
ListNode tail = head;
int carry = 0;
while(l1 != null || l2 != null || carry != 0){
if(l1 != null){
carry = carry + l1.val;
l1 = l1.next;
}
if(l2 != null){
carry = carry + l2.val;
l2 = l2.next;
}
tail.next = new ListNode(carry % 10);
carry = carry / 10;
tail = tail.next;
}
return head.next;
}
}Runtime: 1 ms, faster than 100.00% of Java online submissions for Add Two Numbers.
Memory Usage: 41.3 MB, less than 91.22% of Java online submissions for Add Two Numbers.