LeetCode in Kotlin

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:

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:

Solution

import kotlin.math.abs
import kotlin.math.sqrt

@Suppress("NAME_SHADOWING")
class Solution {
    fun reachNumber(target: Int): Int {
        var target = target
        target = abs(target)
        var `val` = (sqrt(1.0 + 8 * target.toLong()).toInt() - 1) / 2
        var sum = `val` * (`val` + 1) / 2
        while (sum < target || (sum - target) % 2 != 0) {
            `val`++
            sum += `val`
        }
        return `val`
    }
}