-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path002_Add_Two_Numbers.java
80 lines (66 loc) · 1.88 KB
/
002_Add_Two_Numbers.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
ListNode th =null;
ListNode tt = null;
public void addLast(int x){
ListNode nn = new ListNode(x);
if(th == null){
th = nn;
tt = nn;
}else{
tt.next = nn;
tt = nn;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null)return null;
if(l1==null) return l2;
if(l2 == null) return l1;
ListNode c1 = (l1);
ListNode c2 = (l2);
int carry = 0;
int add1 = 0;
while(c1!=null && c2!=null){
int x = c1.val + c2.val + carry;
carry = x/10;
add1 = x%10;
addLast(add1);
c1= c1.next;
c2 = c2.next;
}
if(carry == 0){
tt.next = (c1 == null?c2:c1);
return th;
}
while(c1!=null){
int x = c1.val + carry;
carry = x/10;
add1 = x%10;
addLast(add1);
c1 = c1.next;
}
while(c2!=null){
int x = c2.val + carry;
carry = x/10;
add1 = x%10;
addLast(add1);
c2 = c2.next;
}
if(carry!=0) addLast(carry);
return th;
}
}
*************************************************************************
public class Solution {
// example in leetcode book
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
if (map.containsKey(target - x)) {
return new int[]{map.get(target - x), i};
}
map.put(x, i);
}
throw new IllegalArgumentException("No two sum solution");
}
}