Flip all K-bits of a given number
Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits.
Examples:
Input:N = 1, K = 32
Output: 4294967294
Explanation:
1 in K(= 32) bit representation is (00000000000000000000000000000001)2.
Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10.
Input: N = 0, K = 32
Output: 4294967295
Approach: Follow the steps below to solve the problem:
- Find the value of (1 << (K – 1)) – 1, say X.
- Finally, print the value of (X – N).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void flippingBits(unsigned long N,
unsigned long K)
{
unsigned long X = (1 << (K - 1)) - 1;
N = X - N;
cout << N;
}
int main()
{
unsigned long N = 1, K = 8;
flippingBits(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void flippingBits( long N,
long K)
{
long X = ( 1 << (K - 1 )) - 1 ;
N = X - N;
System.out.print(N);
}
public static void main(String[] args)
{
long N = 1 , K = 8 ;
flippingBits(N, K);
}
}
|
Python3
def flippingBits(N, K):
X = ( 1 << (K - 1 )) - 1
N = X - N
print (N)
if __name__ = = '__main__' :
N, K = 1 , 8
flippingBits(N, K)
|
C#
using System;
class GFG{
static void flippingBits( int N, int K)
{
int X = (1 << (K - 1)) - 1;
N = X - N;
Console.Write(N);
}
public static void Main( string [] args)
{
int N = 1, K = 8;
flippingBits(N, K);
}
}
|
Javascript
<script>
function flippingBits(N, K)
{
let X = (1 << (K - 1)) - 1;
N = X - N;
document.write(N);
}
let N = 1, K = 8;
flippingBits(N, K);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
04 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...