C程序设置数字N的第K位
给定一个数N和一个整数K ,任务是设置数N的第 K 位,即如果第 K 位为 0,则将其设置为 1,如果为 1,则保持不变。
例子:
Input: N = 5, K = 2
Output: 7
Explanation:
5 is represented as 101 in binary and has its second bit 0, so setting it will result in 111 i.e. 7.
Input: N = 5, K = 1
Output: 5
Explanation:
5 is represented as 101 in binary and has its first bit is already 1, so setting it will result in 101 i.e. 5.
方法:解决这个问题的方法是基于位掩码技术,借助按位或运算符。
- 由于任何位与设置位的按位或会导致设置位,即
Any bit
Set bit = Set bit which means,
0 | 1 = 1
1 | 1 = 1
- 因此,对于设置位,最好的办法是对设置的位执行数字的按位或。
n = n | 1 << K
OR
n |= 1 << K
where K is the bit that is to be set
下面是实现上述方法的 C++ 程序——
C++
// C++ program to implement the above approach
#include
// Function to set the
// kth bit of n
int setBit(int N, int K)
{
return (N | (1 << (K - 1)));
}
// Driver code
int main()
{
int N = 5, K = 2;
printf("%d\n", setBit(N, K));
return 0;
}
输出
7