1
long long fun(long long a) { // sum of all natural from 1 to a
2
long long b = a * (a + 1) / 2;
3
return b;
4
}
5

6
class Solution {
7
public:
8
int reachNumber(int target) {
9
long long i = 1, j = pow(10, 5), x = abs(target),
10
ans = 0; // for -ve or +ve positive of a number the minimum no. of
11
// steps from the origin will be same
12

13
while (i <= j) { // binary search to search if x is continous sum of some
14
// natural number starting from 1
15
long long m = (i + j) / 2;
16

17
if (fun(m) == x) {
18
ans = m;
19
}
20
if (x > fun(m)) {
21
i = m + 1;
22
} else {
23
j = m - 1;
24
}
25
}
26

27
if (ans != 0) { // If we found our ans return it
28

29
return ans;
30
} else {
31
// in this for loop i have set the limit too high it can be less then 10^6
32
// as max value j can be is 44723, so loop will never run fully, whatever
33
// the value of j will be, loop will maximum run for 3-10 iterations
34
for (int l = j + 1; l < 100000; l++) { // in the end of binary search we get the value of j(or
35
// high end) as the position of the number(in the
36
// sequence of continous sum of natural number from 1,
37
// i.e. 1, 3,6,10........) whose value is just less
38
// than x(searching element)
39

40
if ((fun(l) - x) % 2 == 0) { // as the total step will be more than x if we go backward from
41
// zero, thing to note is that if we go -ve direction we also
42
// have to come back so we covering even distance
43
ans = l; // when the first fun(l) - x is even that l is our minimum jump
44

45
break; // no need to search further
46
}
47
}
48
}
49

50
return ans;
51
}
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0