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


这道题只需要按照二进制模拟就行了,尽量移最低位的1就会是最优的,

两个特殊情况考虑一下:

低位有0(1100),就移动第一个1的位置。

全是1的情况(1111),注意变二进制长度变量。

#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)