How to count the number of bits to be flipped to convert a number to another number in Kotlin

1 Answer

0 votes
fun countBits(num1: Int, num2: Int): Int {
    var count = 0
    var n1 = num1
    var n2 = num2

    while (n1 > 0 || n2 > 0) {
        val lsb1 = n1 and 1
        val lsb2 = n2 and 1

        if (lsb1 != lsb2) {
            count++
        }

        n1 = n1 shr 1
        n2 = n2 shr 1
    }
    
    return count
}

fun main() {
    var num1 = 2  // 00000010
    var num2 = 17 // 00010001
    println("Number of bits to be flipped: ${countBits(num1, num2)}")

    num1 = 3   // 00000011
    num2 = 221 // 11011101
    println("Number of bits to be flipped: ${countBits(num1, num2)}")
}



/*
run:
  
Number of bits to be flipped: 3
Number of bits to be flipped: 6
  
*/

 



answered Oct 27, 2024 by avibootz
...