Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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

1 Answer

0 votes
object BitCounterToConvertANumberToAnotherNumber  {
  def countBits(num1: Int, num2: Int): Int = {
    var count = 0
    var n1 = num1
    var n2 = num2
    
    while (n1 > 0 || n2 > 0) {
      val lsb1 = n1 & 1
      val lsb2 = n2 & 1

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

      n1 >>= 1
      n2 >>= 1
    }
    
    count
  }

  def main(args: Array[String]): Unit = {
    val num1 = 2  // 00000010
    val num2 = 17 // 00010001
    println(s"Number of bits to be flipped: ${countBits(num1, num2)}")

    val num3 = 3   // 00000011
    val num4 = 221 // 11011101
    println(s"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
...