本文共 2228 字,大约阅读时间需要 7 分钟。
kth number
Here we are going to use to clear Kth bit in the binary representation of a given number.
在这里,我们将使用 清除给定数字的二进制表示形式中的第 K位 。
Problem Statement: To write a C++ program to clear Kth bit of a number.
问题陈述:编写一个C ++程序来清除数字的第 K位。
Constraints: 1<=n<=100
约束:1 <= n <= 100
Example:
例:
Input: Enter number: 11 Enter k: 4 Output: original number before clearing: 11 new number after clearing: 3
Problem Explanation:
问题说明:
Suppose the given number is 11 and the bit to be cleared is 4th bit that is 3 left to the LSB.
假定给定数字为11 ,要清除的位为第 4位,即LSB剩下3 。
Now the binary representation of 11 is:
现在11的二进制表示为:
n = 00001011 mask = 00001000 (left shift 1, three times (4-1) as k=4) Bitwise complement of mask= ~mask = 11110111 n &(~ mask) = 00000011 Hence decimal representation of new number is 3.
This can be explained as follows:
可以解释如下:
Performing & with the ~mask clears Kth bit only as Kth bit in (~mask) is 0.
用〜掩模进行&清除第K位只作为第K在(〜掩模 )为0位。
If X represents bits of n then, 0 & X is always 0. For remaining bits of original number, & with 1 gives the bit itself.
如果X表示n的位,则0和X始终为0。对于原始数字的其余位, &加上1表示该位本身。
Therefore performing bitwise AND of original number with (~mask) clears Kth bit in a number.
因此与执行逐位原来数目的AND(〜mask)将清除第K位的数字。
Algorithm:
算法:
Input the number and Kth bit to be cleared.
输入要清除的数字和第 K位。
Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
左移1- (K-1)次以创建仅设置第 K位的掩码。
Take bitwise complement of the mask.
取掩码的按位补码。
Perform bitwise AND of original number with this mask to clear the Kth bit.
这种面膜进行逐位原来的号码,并清除第 K 个位。
Output the result after bitwise AND in decimal form.
以十进制形式按位与后输出结果。
C++ Implementation:
C ++实现:
#includeusing namespace std;int clearKthBit(int n,int k){ // left shift 1 , (k-1) times to get a mask // in which only kth bit is set int m=1<<(k-1); // bitwise complement of mask m=~(m); // new number after clearing kth bit return (n&m); }//driver program to check the codeint main(){ int num,k; cout<<"Enter number: "; cin>>num; cout<<"Enter k: "; cin>>k; cout<<"original number before clearing: "< <
Output
输出量
Enter number: 11Enter k: 4original number before clearing: 11new number after clearing: 3
翻译自:
kth number
转载地址:http://xzozd.baihongyu.com/