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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
/**
* 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) {
return addPlus(l1,l2,0);
}
public ListNode addPlus(ListNode l1, ListNode l2, int carry){
if(l1==null && l2 ==null&&carry!=0){
return new ListNode(carry);
}else if(l1 == null && l2 == null&& carry == 0)
return null;
else if(l1 == null&&carry==0)
return l2;
else if(l1 == null&&carry!=0){
int sum = l2.val +carry;
l2.val = sum%10;
l2.next = addPlus(l1,l2.next,sum/10);
return l2;
}else if (l2 == null&&carry==0)
return l1;
else if(l2 == null&&carry!=0){
int sum = l1.val +carry;
l1.val = sum%10;
l1.next=addPlus(l1.next,l2,sum/10);
return l1;
}
int sum = l1.val+l2.val+carry;
ListNode head = new ListNode(sum%10);
head.next = addPlus(l1.next,l2.next,sum/10);
return head;
}
}
使用非递归的方式可以获得更加简洁的代码,并且不需要很多if/else
/**
* 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 cur = new ListNode(0);
ListNode head = cur;
int carry = 0;
while(l1!=null||l2!=null||carry!=0){
int sum = (l1==null?0:l1.val) + (l2==null?0:l2.val) + carry;
cur.next = new ListNode(sum%10);
carry = sum /10;
cur = cur.next;
l1= l1==null?l1:l1.next;
l2 = l2==null?l2:l2.next;
}
return head.next;
}
}
Multiply Strings
Add Binary
Sum of Two Integers
Add Strings
Add Two Numbers II
Add to Array-Form of Integer
原文:https://www.cnblogs.com/clnsx/p/12249000.html