Add Two Numbers
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
这道题好像跟算法没啥关系,感觉像是在讲链表的东西。直接上代码。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = l1.val + l2.val;
//返回值
ListNode answer = new ListNode(sum%10);
ListNode p = answer;
l1 = l1.next;
l2 = l2.next;
sum = sum/10;
while (l1 != null || l2 != null)
{
int num1 = 0,num2 = 0;
if(l1 != null)
{
num1 = l1.val;
l1 = l1.next;
}
if(l2 != null)
{
num2 = l2.val;
l2 = l2.next;
}
sum = sum + num1 + num2;
p.next = new ListNode(sum%10);
sum = sum/10;
p = p.next;
}
//如果还有进位,记得把最后进的那位补上
if(sum != 0)
p.next = new ListNode(sum);
return answer;
}
}