Reputation: 13
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
I have tried the following solution but error is Time Limit Exceeded.
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode a = l1;
ListNode b = l2;
ListNode head = new ListNode(0);
ListNode temp = head;
int carry = 0;
while (a != null || b != null)
{
int x = (a!= null) ? a.val : 0;
int y = (b!= null) ? b.val : 0;
int sum = carry + x + y;
carry = sum /10;
ListNode news = new ListNode(sum%10);
temp.next = news;
temp = temp.next;
if (a.next != null) a = a.next;
if (b.next != null) b = b.next;
}
if (carry > 0) {
temp.next = new ListNode(carry);
}
return head.next;
}
}
Upvotes: 0
Views: 78
Reputation: 387
Try modify these two lines:
if (a.next != null) a = a.next;
if (b.next != null) b = b.next;
to
if (a != null) a = a.next;
if (b != null) b = b.next;
Upvotes: 2