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

1 Answer

0 votes
import Foundation

func countBits(_ num1: Int, _ num2: Int) -> Int {
    var count = 0
    var num1 = num1
    var num2 = num2

    while num1 > 0 || num2 > 0 {
        let lsb1 = num1 & 1
        let lsb2 = num2 & 1

        if lsb1 != lsb2 {
            count += 1
        }

        num1 >>= 1
        num2 >>= 1
    }
    
    return count
}

let num1 = 2  // 00000010
let num2 = 17 // 00010001
print("Number of bits to be flipped: \(countBits(num1, num2))")

let num3 = 3   // 00000011
let num4 = 221 // 11011101
print("Number of bits to be flipped: \(countBits(num3, num4))")




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

*/

 



answered Oct 27, 2024 by avibootz
...