nyoj412 Same binary weight (位运算)

 

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
分析:把n转换成二进制,找到第一个为 1 的位置p1(x&-x),从该位置开始再找第一个为 0 的位置p2,统计从p1位置到p2位置 1 的个数 c,然后把位置p2的0转换为1,最后把c-1个 1 加到最低位。
View Code
 1 #include<iostream>
2 #include<cstdio>
3 #include<cmath>
4 using namespace std;
5 int main()
6 {
7 int n;
8 while(cin>>n)
9 {
10 int t,t1,t2;
11 t=n;
12 int tt=n&-n;
13 if(t==tt)
14 {
15 n=n<<1;
16 cout<<n<<endl;continue;
17 }
18 int c=0,s=0;
19 while(t)
20 {
21 t1=t&-t;
22 t=t-t1;
23 t2=t&-t;
24 c++;s+=t1;
25 if(t2>2*t1)
26 {
27 t1=t1<<1;
28 n=n-s+t1+pow(2,c-1)-1;
29 break;
30 }
31 }
32 if(t==0)n=(t1<<1)+pow(2,c-1)-1;
33 cout<<n<<endl;
34 }
35 return 0;
36 }

 
posted @ 2011-11-20 22:31  mtry  阅读(369)  评论(0编辑  收藏  举报