博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
kth number_C ++程序清除数字的Kth位
阅读量:2529 次
发布时间:2019-05-11

本文共 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:

算法:

  1. Input the number and Kth bit to be cleared.

    输入要清除的数字和 K位。

  2. Left shift 1 - (K-1) times to create a mask where only Kth bit is set.

    左移1- (K-1)次以创建仅设置 K位的掩码。

  3. Take bitwise complement of the mask.

    取掩码的按位补码。

  4. Perform bitwise AND of original number with this mask to clear the Kth bit.

    这种面膜进行逐位原来的号码,并清除 K 位。

  5. Output the result after bitwise AND in decimal form.

    以十进制形式按位与后输出结果。

C++ Implementation:

C ++实现:

#include 
using 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/

你可能感兴趣的文章
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>