LeetCode in Kotlin

2571. Minimum Operations to Reduce an Integer to 0

Medium

You are given a positive integer n, you can do the following operation any number of times:

Return the minimum number of operations to make n equal to 0.

A number x is power of 2 if x == 2i where i >= 0.

Example 1:

Input: n = 39

Output: 3

Explanation: We can do the following operations:

Example 2:

Input: n = 54

Output: 3

Explanation: We can do the following operations:

Constraints:

Solution

@Suppress("NAME_SHADOWING")
class Solution {
    fun minOperations(n: Int): Int {
        var n = n
        var count = 0
        while (n > 0) {
            val x = kotlin.math.ln(n.toDouble()) / kotlin.math.ln(2.0)
            if (x % 1.0 < 0.5) {
                n = kotlin.math.abs(n - Math.pow(2.0, x.toInt().toDouble()).toInt())
                count++
            } else {
                n = kotlin.math.abs(n - Math.pow(2.0, (x.toInt() + 1).toDouble()).toInt())
                count++
            }
        }
        return count
    }
}