# 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

#include <stdio.h>
#define LL long long
const int maxn = 105;
int a[maxn], cnt;
void print ( int n )    //test_print
{
for ( int i = 0; i < n; i ++ )
printf ( "%d ", a[i] );
printf ( "\n" );
}
void conver ( LL n, int v )
{
cnt = 0;
while ( n > 0 ) //化为二进制
{
a[cnt ++] = n & 1;
n = n >> 1;
}
//print ( cnt );
}
template < class T >
T Max ( T a, T b )
{
return a > b ? a : b;
}
LL solve ( )
{
int s = 0, i = 0;
LL ret = 0; //有可能是1100,所以先移动到1的位置
while ( i < cnt && ! a[i] )
i ++;
for ( ; i < cnt && a[i]; i ++ ) //找到最近的0,统计1的个数
s ++, a[i] = 0;
a[i ++] = 1;    //将i变为1
cnt = Max ( i, cnt );   //需要重新判断大小例如111
for ( i = 0; i < s-1; i ++ )    //把前面s-1个变成1,肯定全是0了
a[i] = 1;
for ( i = cnt-1; i >= 0; i -- ) //化为整数
ret = ret*2+a[i];
return ret;
}
int main ( )
{
LL n;
while ( ~ scanf ( "%lld", &n ) )
{
conver ( n, 2 );
printf ( "%lld\n", solve ( ) );
}
return 0;
}


• 本文已收录于以下专栏：

## Same binary weight

Same binary weight 时间限制：300 ms  |  内存限制：65535 KB 难度：3 描述 The binary weight of a po...

## Same binary weight

Same binary weight 时间限制：300 ms  |  内存限制：65535 KB 难度：3 描述 The binary weight of a posi...

## nyoj 412 Same binary weight

Same binary weight 时间限制：300 ms  |  内存限制：65535 KB 难度：3 描述 The binary weight of a positive  integer...

## Same binary weight(stl 位运算)

Same binary weight 时间限制：300 ms  |  内存限制：65535 KB 难度：3 描述 The binary weight of a posi...

## nyoj 412Same binary weight

Same binary weight 时间限制：300 ms  |  内存限制：65535 KB 难度：3 描述 The binary weight of a positi...
• yibcs
• 2013-06-20 15:30
• 835

## android weight属性

weight属性可以理解为权重。 关于weight属性有一个计算公式，但是并不需要记住那个公式，所以我也没记住=。=我们只需要记住标准用法就好啦1、用weight设置宽：将控件的width设置为0d...

weight

## 线性布局和表格布局的嵌套使用

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)