-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path754.java
More file actions
54 lines (52 loc) · 1.47 KB
/
754.java
File metadata and controls
54 lines (52 loc) · 1.47 KB
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
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public int reachNumber(int target) {
if (target == 0) {
return 0;
}
target = Math.abs(target);
int max = (int) (Math.sqrt(2) * Math.sqrt(target)) - 1;
int sum = max * (max + 1) / 2;
while (sum < target) {
max++;
sum += max;
}
int diff = sum - target;
if (diff == 0) {
return max;
}
int count = max;
if (diff % 2 == 0) {
return count;
} else {
if (max % 2 == 0) {
return count + 1;
} else {
return count + 2;
}
}
}
}
__________________________________________________________________________________________________
sample 31512 kb submission
class Solution {
public int reachNumber(int target) {
target = Math.abs(target);
if (target == 1) {
return 1;
}
int cur = (int) Math.sqrt(target * 2);
int total = cur * (1 + cur) / 2;
while (total < target) {
++cur;
total += cur;
}
while ((total - target) % 2 != 0) {
++cur;
total += cur;
}
return cur;
}
}
__________________________________________________________________________________________________