一开始在0位置,每一次都可以向左或者向右跳,
第i次能向左或者向右跳严格的i步。
请问从0到x位置,至少跳几次可以到达。
数学题,具体见代码。n*(n-1)/2。
走过头了,回头走,但需要保证奇偶性一致。
代码用rust编写。代码如下:
fn main() {
let ans = reach_number(9);
println!("ans = {}", ans);
}
fn reach_number(mut target: isize) -> isize {
if target == 0 {
return 0;
}
target = abs(target);
let mut l: isize = 0;
let mut r = target;
let mut m:isize = 0;
let mut near = 0;
while l <= r {
m = (l + r) / 2;
if sum(m) >= target {
near = m;
r = m - 1;
} else {
l = m + 1;
}
}
if sum(near) == target {
return near;
}
if ((sum(near) - target) & 1) == 1 {
near += 1;
}
if ((sum(near) - target) & 1) == 1 {
near += 1;
}
return near;
}
fn sum(n: isize) -> isize {
return (n * (n + 1)) / 2;
}
fn abs(a: isize) -> isize {
if a < 0 {
-a
} else {
a
}
}
执行结果如下: