zoukankan      html  css  js  c++  java
  • [POJ] 2453 An Easy Problem [位运算]

    An Easy Problem
     

    Description

    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".

    Input

    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.

    Output

    One integer per line, which is J.

    Sample Input

    1
    2
    3
    4
    78
    0
    

    Sample Output

    2
    4
    5
    8
    83
    

    Source

     
    题解:输入一个整数x,求一个数y,使得y的二进制各位上1的个数和等于x的二进制各位上1的个数和,y>x,y尽量小。直接每次加1,统计各位上1的个数,每次求y末尾是否为1,直接判断y是否为奇数即可,然后y>>=1,右移一位。
    代码:
     1 #include<cstdio>
     2 #include<algorithm>
     3 
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     int p,x,num1,num2;
     9 
    10     while(1) {
    11         num1=0;num2=0;
    12         scanf("%d",&x);
    13         if(!x) break;
    14         p=x;
    15         while(p>0) {
    16             if(p%2!=0) num1++;
    17             p>>=1;
    18         }
    19         while(1) {
    20             x++;
    21             p=x;
    22             num2=0;
    23             while(p>0) {
    24                 if(p%2!=0) num2++;
    25                 p>>=1;
    26             }
    27             if(num2==num1) {
    28                 printf("%d
    ",x);
    29                 break;
    30             }
    31             
    32         }
    33     }
    34     
    35     return 0;
    36 }
  • 相关阅读:
    JS字符串去重
    svn回退到某一版本
    WebStorm格式化代码4个空格设置
    DevExpress中 的DataGrid每一行根据其类型显示控件的种类
    各大系统刷新DNS缓存方法
    Kali Linux中前十名的Wifi攻击工具
    CentOS远程执行漏洞
    判断是否移动端的几种方法
    笔记
    Linux常用命令
  • 原文地址:https://www.cnblogs.com/sxiszero/p/4087545.html
Copyright © 2011-2022 走看看