2. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解题思路:将每位按照个位数字相加的形式,判断是否需要进位
答案:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int val1 = l1.val;
int val2 = l2.val;
int val = val1+val2;
int v = val%10;
int bit = val/10;
ListNode l = new ListNode(v);
ListNode next = l;
ListNode next1=l1.next,next2=l2.next;
while(null != next1 && null != next2 ){
val1 = next1.val;
next1=next1.next;
val2 = next2.val;
next2=next2.next;
if(1==bit){
val = val1 + val2 + 1;
}else{
val = val1 + val2;
}
v = val%10;
bit = val/10;
ListNode node = new ListNode(v);
next.next = node;
next = node;
}
while(null != next1 ){
val1 = next1.val;
next1=next1.next;
if(1==bit){
val = val1 + 1;
}else{
val = val1;
}
v = val%10;
bit = val/10;
ListNode node = new ListNode(v);
next.next = node;
next = node;
}
while(null != next2 ){
val2 = next2.val;
next2=next2.next;
if(1==bit){
val = val2 + 1;
}else{
val = val2;
}
v = val%10;
bit = val/10;
ListNode node = new ListNode(v);
next.next = node;
next = node;
}
if(1 == bit){
ListNode node = new ListNode(1);
next.next = node;
}
return l;
}