All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0701_0800.s0754_reach_a_number.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0701_0800.s0754_reach_a_number;

// #Medium #Math #Binary_Search #2022_03_25_Time_0_ms_(100.00%)_Space_38.8_MB_(86.55%)

/**
 * 754 - Reach a Number\.
 *
 * Medium
 *
 * You are standing at position `0` on an infinite number line. There is a destination at position `target`.
 *
 * You can make some number of moves `numMoves` so that:
 *
 * *   On each move, you can either go left or right.
 * *   During the ith move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
 *
 * Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
 *
 * **Example 1:**
 *
 * **Input:** target = 2
 *
 * **Output:** 3
 *
 * **Explanation:** 
 *
 * 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).
 *
 * **Example 2:**
 *
 * **Input:** target = 3
 *
 * **Output:** 2
 *
 * **Explanation:** 
 *
 * On the 1st move, we step from 0 to 1 (1 step). 
 *
 * On the 2nd move, we step from 1 to 3 (2 steps).
 *
 * **Constraints:**
 *
 * *   -109 <= target <= 109
 * *   `target != 0`
**/
public class Solution {
    public int reachNumber(int target) {
        target = Math.abs(target);
        int val = (((int) Math.sqrt(1.0 + 8 * ((long) target))) - 1) / 2;
        int sum = (val * (val + 1)) / 2;
        while (sum < target || (sum - target) % 2 != 0) {
            val++;
            sum = sum + val;
        }
        return val;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy