¶LeetCode-algorithms2:Add Two Number
Problem :
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.
Example : Input: (2 --> 4 --> 3)+ (5 --> 6 --> 4) ; output : 7 --> 0 --> 8 ; Cause 342 + 465 = 807
First Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Node<E extends Comparable<E>> {
public E value;
public Node<E> next;
public Node() {
}
public Node(E value) {
this.value = value;
}
public boolean compare(Node<E> node) {
return this.value.compareTo(node.value) >= 0;
}
}
public static Node<Integer> linkSum(Node<Integer> headA, Node<Integer> headB){
int sumResult= 0 ;
//number used to calculate the number digit
int sq=0;
while(headA!=null && headB!=null){
//the digit
int munumber = (int) Math.pow(10,sq);
int anum = headA.value*munumber;
int bnum = headB.value*munumber;
//sum each result to get the final result
sumResult=sumResult + anum+bnum;
sq++;
headA=headA.next;
headB=headB.next;
}
//show result by LinkList,but maybe it`s just beacuse this solution was not so good
Node<Integer> head = new Node<>();
Node<Integer> tail = new Node<>();
int i=0;
while(i<sq){
int munumber = (int) Math.pow(10,i);
Node<Integer> temp = new Node<>((sumResult%(munumber*10))/munumber);
tail.next = temp;
if(head.next==null){
head.next=tail.next;
}
tail=tail.next;
i++;
}
return head.next;
}The code to show the number by linklist maybe redundant,or i can get the linklist result in number calculate
Second Answer
- //TODO