LeetCode in Kotlin

2749. Minimum Operations to Make the Integer Zero

Medium

You are given two integers num1 and num2.

In one operation, you can choose integer i in the range [0, 60] and subtract 2i + num2 from num1.

Return the integer denoting the minimum number of operations needed to make num1 equal to 0.

If it is impossible to make num1 equal to 0, return -1.

Example 1:

Input: num1 = 3, num2 = -2

Output: 3

Explanation: We can make 3 equal to 0 with the following operations:

It can be proven, that 3 is the minimum number of operations that we need to perform.

Example 2:

Input: num1 = 5, num2 = 7

Output: -1

Explanation: It can be proven, that it is impossible to make 5 equal to 0 with the given operation.

Constraints:

Solution

class Solution {
    fun makeTheIntegerZero(num1: Int, num2: Int): Int {
        val n1 = num1.toLong()
        val n2 = num2.toLong()
        for (i in 0..60) {
            val target = n1 - n2 * i
            val noOfBits = java.lang.Long.bitCount(target)
            if (i.toLong() in noOfBits..target) {
                return i
            }
        }
        return -1
    }
}