NYOJ 412(bitset)

简介:   Same binary weight 时间限制:300 ms | 内存限制:65535 KB 难度:3   描述 The binary weight of a positive integer is the number of 1's in its binary representation.

 

Same binary weight

时间限制: 300 ms | 内存限制: 65535 KB
难度: 3
 
描述

The binary weight of a positive integer is the number of 1's in its binary representation.for example,the decmial number 1 has a binary weight of 1,and the decimal number 1717 (which is 11010110101 in binary) has a binary weight of 7.Give a positive integer N,return the smallest integer greater than N that has the same binary weight as N.N will be between 1 and 1000000000,inclusive,the result is guaranteed to fit in a signed 32-bit interget.

 
输入
The input has multicases and each case contains a integer N.
输出
For each case,output the smallest integer greater than N that has the same binary weight as N.
样例输入
1717
4
7
12
555555
样例输出
1718
8
11
17
555557
 1 //第一个01,变为10,1的右边有n个1,把1变为0,再次把 右边的n为0变为1,答案为所求 
 2 #include <iostream>
 3 #include <bitset>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int i,j,k;
 9     int num;
10     while(cin>>num)
11     {
12         bitset <32> Q;
13         i=0;
14         while(num>0)//大于0,更安全 
15         {
16             if(num&1)
17                 Q.set(i);//默认设置为1 
18             num/=2;
19             i++;
20         }
21         for(j=0;j<i;j++)
22         {
23             if(Q.test(j)&&!Q.test(j+1))//test()函数返回在pos上的位的值。
24             {
25                 Q.flip(j);
26                 Q.flip(j+1);
27                 break;
28             }
29         }
30         int count=0;
31         for(i=0;i<j;i++)
32         {
33             if(Q.test(i)) 
34             {
35                 count++;
36                 Q.flip(i);
37             }
38         }
39         for(i=0;i<count;i++)
40             Q.flip(i);
41         //printf("%u\n",Q.to_ulong());
42         cout<<Q.to_ulong()<<endl;
43     }
44     return 0;
45 }        

 

目录
相关文章
|
6月前
|
C++ 容器
bitset(C++实现)
bitset(C++实现)
37 0
|
人工智能
【待补】UPC No Need(二分+bitset || 背包dp)
【待补】UPC No Need(二分+bitset || 背包dp)
40 0
|
存储 算法 Java
|
存储 算法 Java
bitset使用
17.10使用序列1、2、3、5、8、13、21初始化一个bitset,将这些位置置位。对另一个bitset进行默认初始化,并编写一小段程序将其恰当的位置位。 #include #include using namespace std; int main() { bitset...
880 0
|
计算机视觉
NYOJ 289
  苹果 时间限制:3000 ms  |  内存限制:65535 KB 难度:2   描述 ctest有n个苹果,要将它放入容量为v的背包。给出第i个苹果的大小和价钱,求出能放入背包的苹果的总价钱最大值。
727 0
NYOJ 93
  汉诺塔(三) 时间限制:3000 ms | 内存限制:65535 KB 难度:3   描述 在印度,有这么一个古老的传说:在世界中心贝拿勒斯(在印度北部)的圣庙里,一块黄铜板上插着三根宝石针。
573 0
|
测试技术
NYOJ 202
  红黑树 时间限制:3000 ms | 内存限制:65535 KB 难度:3   描述 什么是红黑树呢?顾名思义,跟枣树类似,红黑树是一种叶子是黑色果子是红色的树。。。 当然,这个是我说的。
797 0