Same binary weight

翻译 2015年11月19日 21:55:04
描述

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;
}



相关文章推荐

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...

Same binary weight

Same binary weight 时间限制:300 ms  |  内存限制:65535 KB 难度:3 描述 The binary weight of a po...
  • CTTACM
  • CTTACM
  • 2015年05月13日 14:15
  • 183

leetcodey -day25 Binary Tree Level Order Traversal & Symmetric Tree & Same Tree

1、  Binary Tree Level Order Traversal Given a binary tree, return the level order traversal o...

ios Embedded binary is not signed with the same certificate as the parent app. 解决办法

上传应用的时候出现错误: error: Embedded binary is not signed with the same certificate as the pare...

Copying Clients Within the Same System

  • 2008年11月21日 12:39
  • 221KB
  • 下载

get/close not same thread Druid 连接池一个设置没设置对引发的血案

我就郁闷了,1000W+数据审核每次总是到一半就出这么个错,仔细找找原来是一个配置项的小问题,removeAbandonedTimeout 这个代表你从连接池取出一个连接多少秒之后你还没还回来,那就强...

DLPC and SAMe combined prevent leptin

  • 2012年10月01日 14:30
  • 297KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Same binary weight
举报原因:
原因补充:

(最多只允许输入30个字)