Runtime: 2 ms, faster than 54.87% of Java online submissions for Add Two Numbers.
Memory Usage: 39.5 MB, less than 71.39% of Java online submissions for Add Two Numbers.
public class CommonTest {
@Test
public void test(){
int i1[] = {5,6};
int i2[] = {5,9,1};
ListNode test = addTwoNumbers(oneNode(i1), oneNode(i2));
System.out.println(test);
}
public ListNode oneNode(int[] value){
ListNode node = new ListNode(value[0]);
if (value.length == 1){
return node;
}
ListNode nextNode = node.next = new ListNode(value[1]);
for (int i = 2 ; i < value.length ; i ++){
nextNode = nextNode.next = new ListNode(value[i]);
}
return node;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int[] sumInt = new int[2];
ListNode headNode = new ListNode(sumInt[0]);
ListNode l1NextNode = l1;
ListNode l2NextNode = l2;
ListNode nextNode = headNode;
while (l1NextNode != null || l2NextNode != null || sumInt[0] == 1){
if (l1NextNode == null){
l1NextNode = new ListNode(0);
}
if (l2NextNode == null){
l2NextNode = new ListNode(0);
}
sumInt = addTwoInt(l1NextNode.val, l2NextNode.val, sumInt[0]);
nextNode.val = sumInt[1];
l1NextNode = l1NextNode.next;
l2NextNode = l2NextNode.next;
if (l1NextNode != null || l2NextNode != null || sumInt[0] == 1){
nextNode = nextNode.next = new ListNode(0);
}
}
return headNode;
}
private int[] addTwoInt(int i1, int i2, int one){
int[] retInt = new int[2];
int sum = i1 + i2 + one;
if (sum >= 10){
retInt[0] = 1;
retInt[1] = sum - 10;
} else {
retInt[0] = 0;
retInt[1] = sum;
}
return retInt;
}
}