NYOJ 412 Same binary weight

描述

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的位置i,再求在1出现后(即从i开始)最先出现的0的位置j,交换j跟j-1的值(俺考虑的加法),再将j-1后到i位置移到最低位即可,中间涉及位运算。
注:t&-t 的值  如下例:4=(100)--二进制 -4=(100)---(二进制)(补码) 4 &-4=(100)---(二进制)
View Code
 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5    unsigned int n;//无符号整数占4个字节(32位)
 6    while(cin>>n)
 7    {
 8       int t=n&-n;
 9       if(n==t)
10       {
11           cout<<(n<<1)<<endl;
12           continue;
13       }
14       int i=0,j,high,low=0;
15       while(((n>>i)&1)==0)++i;//1=i
16           j=i;
17       while(j<=31&&((n>>j)&1)==1)++j;//0=j+1  
18        high=((n>>(j-1))<<(j-1))+(1<<(j-1));//高位
19       if( j>=2)
20          low =((n<<(33-j))>>(33-j+i));//低位
21       cout<< high+low<<endl;
22    }
23 return 0;
24 }

 


 

posted on 2012-07-14 15:46  L_S_X  阅读(188)  评论(0编辑  收藏  举报

导航