754.Reach A Number
754.Reach A Number
难度:Easy
You are standing at position 0 on an infinite number line. There is a goal at position target.
On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.
Return the minimum number of steps required to reach the destination.
可以见得,最快的方式是直接等差数列递增过去。但是有时候会超过给定值,这时候就需要把一个数变为相反数。 变为相反数之后,总体值与原来相差两倍该变化值。因此如果递增和与给定值之差为偶数,则只需要改一个即可。如果为奇数,继续往后面走,知道为偶数即可。 正数与负数一样。 还需要注意整型溢出情况。
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了81.69%的用户
Last updated
Was this helpful?