Leetcode_754_到达终点数字_模拟

12/18

用公式计算出x(sum[1,x]>=target)
如果之间的差为偶数,直接返回x
(比如差值是2,我们只需要把+1变成-1,差值是4,我们只需把+2变成-2)
如果差值是奇数,
如果总步数为偶数,
	通过翻转我们能获得target-1,我们要走一步(翻转最后一步,并再往前走一步)
如果总步数为奇数,
	通过翻转我们能获得target+1,我们要走两步(先前进n步再后退n+1步数)
class Solution {
    
    
    public int reachNumber(int target) {
    
    
        target = Math.abs(target);
        int x = (int) Math.ceil((Math.sqrt(1 + 8 * (double) target) - 1) / 2);
        int cha = x * (x + 1) / 2 - target;
        return cha % 2 == 0 ? x : x % 2 == 0 ? x + 1 : x + 2;
    }
}

猜你喜欢

转载自blog.csdn.net/HDUCheater/article/details/111376968