位运算(an easy problem)

描述
As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form.

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1's in whose binary form is the same as that in the binary form of I.

For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 '1's. The minimum integer, which is greater than "1001110" and also contains 4 '1's, is "1010011", i.e. "83", so you should output "83".

输入
One integer per line, which is I (1 <= I <= 1000000).

A line containing a number "0" terminates input, and this line need not be processed.

输出
One integer per line, which is J.
样例输入

1
2
3
4
78
0

样例输出

2
4
5
8
83

看了这个大篇幅的“英文”文章,实在是头疼,有一说一我是用有道翻译过来才看明白。
此题主要为运算来解题,代码入下:

#include <iostream>
using namespace std;
int f(int n)  //定义一个函数来统计输入数n的二进制形式中1的个数
{
    int s=0;
    for(int i=0;i<64;i++){
        if(n>>i&1)  //此处使用右移运算符,每次循环将最右侧的数跟1进行按位&,若同为1则s++
        s++;}
    return s;}
int main()
{
    int n;
    while(cin>>n){
        if(n==0) break;   //遇到零就结束while
        for(int j=n+1;;j++){
            if(f(j)==f(n)){
            cout<<j<<endl;
            break;}
            }
        }
}

举例说明总结位运算:
(1)按位&:21&18 两位同为1则取1,有一位为0,则取0
21:0001 0101
18:0001 0010
0001 0000 ->16
通常用来将变量中的某些位清零且同时保留其它不变
也可用来获取变量中的某一位
(2)按位|:21|18 只要有一位为1,就取1
21:0001 0101
18:0001 0010
0001 0111 ->23
用来将某变量中的某些位置置成1,且保留其它位不变
(3)按位^:21^18 两位相同则取0,不同则取1
21:0001 0101
18:0001 0010
0000 0111 ->7
用来将变量中的某些位取反,且保留其他位不变
(4)右移运算符/左移运算符
右移:变量 n>>y 移动的位数
左移:变量 n<<y 移动的位数
将变量n的各二进位全部移动y位的得到的值,左移时,高位丢弃,低位补0,a的值不因运算符的改变而改变
右移时,如果原符号位为1,则右移时高位补充1,如果原符号位为0,则右移时高位补充0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值