NYOJ 412 Same binary weight(<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.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
资料参考:<bitset> http://www.cplusplus.com/reference/bitset/bitset/
思路:转化成二进制数,从后向前 找到第一个1(c1),第一个01(c2,c2表示0的位置)即得到0后1的长度值为c2-c1,将01转化成10,后面全部置0,然后将c2-c1-1个低位置1即可
代码1:
 1  
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cmath>
 5 #include <bitset>
 6 using namespace std;
 7 int main()
 8 {
 9     int n,temp,i,j,counter;
10     while(~scanf("%d",&n))
11     {
12         bitset<32> q; //32位,全为0
13         i=0;
14         //将n转成二进制
15         while(n)
16         {
17             if(n&1)
18             q.set(i);
19             i++;
20             n>>=1;
21         }
22         //下面找到从右到左第一个“01”,并置为“10”
23         counter=0;
24         for(j=0;j<i;j++)
25         {
26             if(q.test(j))
27             {
28                 counter++;
29                 q.reset(j);
30                 if(!q.test(j+1))//找到“01”首个立即退出
31                 {
32                     q.set(j+1);
33                     break;
34                 }
35             }
36         }
37         for(j=0;j<counter-1;j++)//最后1的个数应该是counter-1个
38             q.set(j);
39        cout<<q.to_ulong()<<endl;
40     }
41  return 0;
42 }
43         
View Code

代码2(oj上最优代码):

 1  #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <bitset>
 5 using namespace std;
 6 int main()
 7 {
 8    int  x,b,t,c,m,r;
 9    while(scanf("%d",&x)!=EOF)
10    {
11       b=x&(-x);//b的值是:只保留最低位的1,前面的1全部置0
12       t=x+b;//t的值是:将x第一个01变成10,并将后面的全部变成0
13       c=x^t;      //异或,将,第一个01变成11,前边的置0,后面的保留
14       m=(c>>2)/b;//将c向右移(2+log2(b))即10后面1的个数(记录在m中)
15       r=t|m;     //t的末尾置 log2(m+1)个1
16       printf("%d\n",r);
17    }
18 }
19 //不懂,测试下        
View Code

 

posted on 2013-08-29 12:56  落水寒冰  阅读(233)  评论(0编辑  收藏  举报

导航