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 itselsf.

Approach 1:
public class ListNode{ int val; ListNode next; ListNode(int x){ val=x; } }
public ListNode addTwoNumbers(ListNode l1,ListNode l2){ ListNode listNode=new ListNode(0); ListNode node=listNode; 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; int carry=sum/10; node.next=new ListNode(sum%10); node=node.next; if(l1!=null){ l1=l1.next; } if(l2!=null){ l2=l2.next; } } if(carry>0){ node.next=new ListNode(carry); } return listNode.next; }
posted on
浙公网安备 33010602011771号