Hackerrank: Flipping bits

You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset).

Take 1 for example, as unsigned 32-bits is 00000000000000000000000000000001 and doing the flipping we get 11111111111111111111111111111110 which in turn is 4294967294.

This can be easily solve using the XOR operation.
What is XOR?
XOR/ExclusiveOR is a logical operation that outputs true only when inputs differ (one is true, the other is false).

XOR truth table
Input Output
A B
0 0 0
0 1 1
1 0 1
1 1 0

To achieve flipping, we need to take a 32 bit number in which all the bits are set to 1.
This number is going to be 232-1 which is 4294967295, in binary format this would look like
11111111 11111111 11111111 11111111

If our input number is 1 and we need to flip it, then output of,
(11111111 11111111 11111111 11111111) XOR (00000000 00000000 00000000 00000001)
is
11111111 11111111 11111111 11111110 which is the expected output !!

Below is the scala code for the same

object FlippingBits {
  def main(args:Array[String]):Unit=
  {
    var v=BigInt(1 )
    var twoRaisedTo32Minus1 = scala.math.pow(2, 32).toLong-1; //11111111 11111111 11111111 11111111 , 4294967295

    val sc = new java.util.Scanner (System.in); 
    var row_col_numLines = sc.nextLine().toInt //Read number of entries
    var numbers:Array[Long] = new Array[Long](row_col_numLines)
    for(i<-0 to row_col_numLines-1)
      numbers(i) = sc.nextLine().toLong        //Read the numbers to be flipped
    for(i<-0 to row_col_numLines-1)
      println(twoRaisedTo32Minus1^numbers(i))  //Flip the numbers using XOR operator (^)
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *