You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
译:给定两个用列表表示的非负整数,整数逆序存储并且每个节点存储一个整数位,求两个数的和并用列表返回。
整数加法问题,需要考虑进位和余数问题,
利用变量carryBit = 0存储进位。
1. 如果l1!=null && l2!=null,那么计算(节点及进位的和%10)添加到r中并计算新的进位
2. 如果l1!=null,那么把l1的数加进位添加到r中
3. 如果l2!=null,那么把l2的数加进位添加到r中
4. 如果l1==null&&l2==null&&carryBit!=null,把1添加到r中
/**
* Definition for singly-linked list.
*/
public class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode tmpL1 = null;
public static ListNode tmpL2 = null;
public static ListNode sumListNode = null;
public Solution(){
tmpL1 = new ListNode(2);
tmpL1.next = new ListNode(4);
tmpL1.next.next = new ListNode(8);
tmpL1.next.next.next = new ListNode(9);
tmpL2 = new ListNode(5);
tmpL2.next = new ListNode(6);
tmpL2.next.next = new ListNode(4);
}
/**
* carryBit = 0;
* 如果l1!=null && l2!=null,那么计算和+进位添加到r中并计算新的进位
* 如果l1!=null,那么把l1的数加进位添加到r中
* 如果l2!=null,那么把l2的数加进位添加到r中
* 如果l1==null&&l2==null&&carryBit!=null,把1添加到r中
*
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carryBit = 0,tmpBit = 0,tmpSum = 0;
ListNode tmpL1=l1,tmpL2=l2,sumListHead = null,sumListNode = new ListNode(0);
sumListHead = sumListNode;
while(tmpL1!=null&&tmpL2!=null){
tmpSum = tmpL1.val+tmpL2.val+carryBit;
tmpBit = tmpSum%10;
carryBit = tmpSum/10;
ListNode newBit = new ListNode(tmpBit);
sumListNode.next = newBit;
sumListNode = sumListNode.next;
tmpL1 = tmpL1.next;
tmpL2 = tmpL2.next;
}
ListNode tmpL = null;
if(tmpL1!=null) tmpL = tmpL1;
if(tmpL2!=null) tmpL = tmpL2;
while(tmpL!=null){
tmpSum = tmpL.val+carryBit;
tmpBit = tmpSum%10;
carryBit = tmpSum/10;
ListNode newBit = new ListNode(tmpBit);
sumListNode.next = newBit;
sumListNode = sumListNode.next;
tmpL = tmpL.next;
}
if(carryBit == 1){
ListNode newBit = new ListNode(1);
sumListNode.next = newBit;
sumListNode = sumListNode.next;
}
return sumListHead.next;
}
public static void main(String [] args){
//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
Solution s = new Solution();
sumListNode = s.addTwoNumbers(tmpL1,tmpL2);
while(sumListNode!=null){
System.out.println(sumListNode.val);
sumListNode = sumListNode.next;
}
}
}
f(n) = O(L1.length+L2.length)
7
0
3
0
1
原文地址:http://blog.csdn.net/baidu_22502417/article/details/46641037