Flipping bits HackerRank Problem Solution

In this Flipping bits HackerRank problem, You will be given a list of 32 bit unsigned integers. Flip all the bits ( and ) and return the result as an unsigned integer.

Example

. We’re working with 32 bits, so:

Return .

Function Description

Complete the flippingBits function in the editor below.

flippingBits has the following parameter(s):

  • int n: an integer

Returns

  • int: the unsigned decimal integer result

Input Format

The first line of the input contains , the number of queries.
Each of the next  lines contain an integer, , to process.

Constraints

Sample Input

3 
2147483647 
1 
0

Sample Output

2147483648 
4294967294 
4294967295

Explanation

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

Flipping bits HackerRank Problem Solutions

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in JavaScript

function flippingBits(n) {
    let bin = n.toString(2);
    while (bin.length < 32) {
        bin = '0' + bin;
    }
    const binArr = bin.split('').map(digit => {
        if (digit === '0') {
            return 1;
        }
        return 0;
    });
    return parseInt(binArr.join(''), 2);
}

Problem Solution in Python

def flippingBits(n):
    binAr = list(map(int, format(n, '032b')))
    count = len(binAr)
   
    decimal = 0
    power = count - 1
   
    for elem in binAr:
        flippedElem = 1 if elem == 0 else 0
        decimal += flippedElem * 2 ** power
        power -=1  
       
    return decimal

Problem Solution in Java

public static long flippingBits(long n) {
        long ans = 0;
        for(int i=31;i>=0;i--) {
            ans |= ((n & (1L << i)) ^ (1L << i));
        }
        return ans;
    }

Leave a Comment