Input: target =2Output: 3Explanation:
On the 1st move, we step from 0 to 1(1 step).On the 2nd move, we step from 1 to -1(2 steps).On the 3rd move, we step from -1 to 2(3 steps).
At each move, you can go left or right, and the step size increases by 1 each time. The sum of the first k natural numbers is k*(k+1)/2. We want to find the smallest k such that we can reach target (possibly by flipping the direction of some moves). The key is: if the sum overshoots the target, and the difference is even, we can flip some moves to reach exactly target.
classSolution {
publicintreachNumber(int target) {
target = Math.abs(target);
int sum = 0, k = 0;
while (sum < target || (sum - target) % 2 != 0) {
++k;
sum += k;
}
return k;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funreachNumber(target: Int): Int {
var t = kotlin.math.abs(target)
var sum = 0var k = 0while (sum < t || (sum - t) % 2!=0) {
k++ sum += k
}
return k
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defreachNumber(self, target: int) -> int:
t = abs(target)
sum_ =0 k =0while sum_ < t or (sum_ - t) %2!=0:
k +=1 sum_ += k
return k
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnreachNumber(target: i32) -> i32 {
letmut t = target.abs();
letmut sum =0;
letmut k =0;
while sum < t || (sum - t) %2!=0 {
k +=1;
sum += k;
}
k
}
}