forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReachANumber.java
More file actions
34 lines (31 loc) · 785 Bytes
/
ReachANumber.java
File metadata and controls
34 lines (31 loc) · 785 Bytes
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
class ReachANumber {
// TC O(1)
public int reachNumber(int target) {
if(target<0){
target = -target;
}
int step =0;
int totalSum = 0;
while(target > totalSum){
step++;
totalSum += step;
}
if(target == totalSum){
return step;
} else {
int difference = totalSum - target;
if(difference % 2==0){
return step;
} else {
// difference is odd
if((step+1)%2==1){
return step +1;
} else {
// step +1 is even
// step + 2 is odd
return step+2;
}
}
}
}
}