给定一个整数N ,任务是找到一个整数M ,该整数是通过取N中最右边的置位而形成的,即M中唯一的置位将是N中最右边的置位,其余的这些位将不被置位。
例子:
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
方法:
- 存储x = n&(n – 1) ,这将使n中从右开始的第一个置位位置未设置。
- 现在,更新n = n ^ x以设置更改后的位,并取消设置所有其他整数(即所需的整数)。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the integer formed
// by taking the rightmost set bit in n
int firstSetBit(int n)
{
// n & (n - 1) unsets the first set
// bit from the right in n
int x = n & (n - 1);
// Take xor with the original number
// The position of the 'changed bit'
// will be set and rest will be unset
return (n ^ x);
}
// Driver code
int main()
{
int n = 12;
cout << firstSetBit(n);
return 0;
}
Java
// Java implementation of the approach
class geeks
{
// Function to return the integer formed
// by taking the rightmost set bit in n
public static int firstSetBit(int n)
{
// n & (n - 1) unsets the first set
// bit from the right in n
int x = n & (n-1);
// Take xor with the original number
// The position of the 'changed bit'
// will be set and rest will be unset
return (n ^ x);
}
// Driver Code
public static void main (String[] args)
{
int n = 12;
System.out.println(firstSetBit(n));
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python3 implementation of the approach
# Function to return the integer formed
# by taking the rightmost set bit in n
def firstSetBit(n):
# n & (n - 1) unsets the first set
# bit from the right in n
x = n & (n - 1)
# Take xor with the original number
# The position of the 'changed bit'
# will be set and rest will be unset
return (n ^ x)
# Driver code
n = 12
print(firstSetBit(n))
# This code is contributed by mohit kumar 29
C#
// C# implementation of the approach
using System;
class geeks
{
// Function to return the integer formed
// by taking the rightmost set bit in n
public static int firstSetBit(int n)
{
// n & (n - 1) unsets the first set
// bit from the right in n
int x = n & (n-1);
// Take xor with the original number
// The position of the 'changed bit'
// will be set and rest will be unset
return (n ^ x);
}
// Driver Code
public static void Main ()
{
int n = 12;
Console.WriteLine(firstSetBit(n));
}
}
// This code is contributed by
// anuj_67..
Javascript
输出:
4