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的二进制数最末位0和1的位数:
-
#include<iostream>
#include<cstdio>using namespace std;
int main()
{
int n,i,n0,cnt1,cnt2,k,l,N;while(scanf("%d",&n)!=EOF)
{
cnt1=0;
N=n;
while(n)
{
if(n%2!=0)
break;
cnt1++;
n/=2;
}
cnt2=cnt1;
while(n)
{
if(n%2==0)
break;
cnt2++;
n/=2;
}
k=l=1;
for(i=1; i<=cnt1; i++)
k*=2;
k-=1;
for(i=1; i<=cnt2-cnt1-1; i++)
l*=2;
n0=k+l;
printf("%d\n",n0+N);
}
return 0;
}