nyoj 412-Same binary weight (bitset ,to_ulong())

412-Same binary weight


内存限制:64MB 时间限制:0ms 特判: No
通过数:2 提交数:3 难度: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

C/C++  AC:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <cmath>
 6 #include <stack>
 7 #include <set>
 8 #include <map>
 9 #include <queue>
10 #include <climits>
11 #include <bitset>
12 #define PI 3.1415926
13 
14 using namespace std;
15 const int MY_MAX = 35;
16 int N, M;
17 
18 int main()
19 {
20     while (cin >>N)
21     {
22         bitset <32> A(N);
23         int pos = 32, cnt = 0;
24         for (int i = 0; i <= 32; ++ i)
25         {
26             if (A[i] && !A[i + 1])
27             {
28                 A[i] = 0, A[i + 1] = 1;
29                 pos = i;
30                 break;
31             }
32             if (A[i])
33                 cnt ++;
34         }
35 
36         for (int i = 0; i < pos; ++ i)
37         {
38             if (cnt)
39             {
40                 A[i] = 1;
41                 cnt --;
42             }
43             else
44                 A[i] = 0;
45         }
46         printf("%d\n", A.to_ulong());
47     }
48 }

 

posted @ 2018-07-21 10:26  GetcharZp  阅读(184)  评论(0编辑  收藏  举报