Number formed by the rightmost set bit in N
Last Updated :
04 Jul, 2022
Given an integer N, the task is to find an integer M formed by taking the rightmost set bit in N i.e. the only set bit in M will be the rightmost set bit in N and the rest of the bits will be unset.
Examples:
Input: N = 7
Output: 1
7 = 111, the number formed by the last set bit is 001 i.e. 1.
Input: N = 10
Output: 2
10 = 1010 -> 0010 = 2
Input: N = 16
Output: 16
Approach:
- Store x = n & (n – 1) which will unset the first set bit from the right in n.
- Now, update n = n ^ x to set the changed bit and unset all the others which is the required integer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int firstSetBit( int n)
{
int x = n & (n - 1);
return (n ^ x);
}
int main()
{
int n = 12;
cout << firstSetBit(n);
return 0;
}
|
Java
class geeks
{
public static int firstSetBit( int n)
{
int x = n & (n- 1 );
return (n ^ x);
}
public static void main (String[] args)
{
int n = 12 ;
System.out.println(firstSetBit(n));
}
}
|
Python3
def firstSetBit(n):
x = n & (n - 1 )
return (n ^ x)
n = 12
print (firstSetBit(n))
|
C#
using System;
class geeks
{
public static int firstSetBit( int n)
{
int x = n & (n-1);
return (n ^ x);
}
public static void Main ()
{
int n = 12;
Console.WriteLine(firstSetBit(n));
}
}
|
Javascript
<script>
function firstSetBit(n)
{
let x = n & (n - 1);
return (n ^ x);
}
let n = 12;
document.write(firstSetBit(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...