假设您正站在无限数线上的位置0。现在在目标位置有一个目标。在这里,每步操作都可以转到左侧或右侧。在第n步(从1开始)中,您需要执行n步。我们必须找到到达目的地所需的最少步骤。因此,如果输入类似于target = 3,那么我们需要2个步骤。从0到1,从1到3。
为了解决这个问题,我们将遵循以下步骤-
target:= | target |,cnt:= 0
当目标> 0时,
减少cnt 1
目标:=目标–cnt
如果目标是偶数,则返回cnt,否则返回cnt + 1 + cnt mod 2
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int reachNumber(int target) {
target = abs(target);
int cnt = 0;
while(target > 0){
target -= ++cnt;
}
return target % 2 == 0? cnt : cnt + 1 + cnt % 2;
}
};
main(){
Solution ob;
cout << (ob.reachNumber(3));
}3
输出结果
2