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
杨辉三角(vector)
题目: 输入一个数字n,实现输出n行对应的杨辉三角数;
84 0
|
存储 算法 Java
[LeetCode]--190. Reverse Bits(不是很懂的位运算)
补充知识,Java的位运算(bitwise operators) Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 96
1624 0
|
存储 算法 Java
bitset使用
17.10使用序列1、2、3、5、8、13、21初始化一个bitset,将这些位置置位。对另一个bitset进行默认初始化,并编写一小段程序将其恰当的位置位。 #include #include using namespace std; int main() { bitset...
877 0
|
API
NYOJ 540
  为了给学弟学妹讲课,我水了一道题…… import java.util.Arrays; import java.util.Scanner; public class NYOJ540 { public static void main(String[] args) { ...
799 0
|
人工智能
NYOJ 55
  懒省事的小明 时间限制:3000 ms | 内存限制:65535 KB 难度:3   描述 小明很想吃果子,正好果园果子熟了。在果园里,小明已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。
925 0