POJ - 2453

As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form.

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1's in whose binary form is the same as that in the binary form of I.

For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 '1's. The minimum integer, which is greater than "1001110" and also contains 4 '1's, is "1010011", i.e. "83", so you should output "83".

Input

One integer per line, which is I (1 <= I <= 1000000).

A line containing a number "0" terminates input, and this line need not be processed.

Output

One integer per line, which is J.

Sample Input

1
2
3
4
78
0

Sample Output

2
4
5
8
83

我不会位运算和贪心,我的思路是先把数转换为二进制数,放到一个数组里,因为1的个数要保持不变,所以先找到第一个1,还有要找的数比输入的数大,所以这个1不能与后面的0互换位置,因此,第一个1要与再次遇到的第一个0互换位置,这保证大于输入的数,又因为要找最小的数,所以只要把换过位置1,后面的1全放在最后就是结果了,下面是代码。

#include<iostream>
#include<cstring>
using namespace std;
bool an[21];
void zhuanhua(int n)    //转化为2进制数
{
    memset(an,0,sizeof(an));
    int i=0;
    an[i]=n%2;
    n=n/2;
    while(n)
    {
        i++;
        an[i]=n%2;
        n=n/2;
    }
//    for(i=0;i<21;i++)
//    {
//        cout<<an[i];
//    }
//    cout<<endl;

int xz(void)     //寻找数 
{
    int i,k=0;
    for(i=0;i<21;i++)  // 寻找第一个1 
    {
        if(an[i])
        {
            break;
        }
    }
     for(;i<21;i++)     // 寻找从第一个1开始的第一个零 
     {
         if(an[i])
         {
             k++;
         }
         if(!an[i])
         {
             an[i]=1;
             if(i-1>=0)
             {
                 an[i-1]=0;
             }
             break;
         }
     }
//              for(int q=0;q<21;q++)
//    {
//        cout<<an[q];
//    }
//    cout<<endl;
     k=k-1;
     for(int j=0;j<i;j++)   //化为最小值 
     {
         if(k>0)
         {
             an[j]=1;
         }
         else
         {
             an[j]=0;
         }
         k--;
     }
//         for(i=0;i<21;i++)
//    {
//        cout<<an[i];
//    }
//    cout<<endl;
     int a=0,kid;
     for(i=0;i<21;i++)
     {
         if(an[i])
         {
             kid=1;
             for(int j=0;j<i;j++)
             {
                 kid=kid*2;
             }
             a+=kid;
         }
     }
     return a;
}
int main()
{
    int n,result;
    cin>>n;
    while(n)
    {
        zhuanhua(n);
        result=xz();
        cout<<result<<endl;
        cin>>n;
    }
    return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值