华为OD机试 - 找数字【C++】

题目描述

小扇和小船今天又玩起来了数字游戏,小船给小扇一个正整数n (1<=n<=1e9),小扇需要找到一个比n大的数字m,使得m和n对应的二进制中1的个数要相同(如4对应二进制100,8对应二进制1000,1的个数都为1),现在求m的最小值。

输入

输入一行输入一个正整数n (1 <= n <= 1e9)。

输出

输出一个正整数m。

#include <stdio.h>
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <math.h>
using namespace std;

bool GetNextByteNum(const int iNumSrc,int& iNumDst)
{
	char strNumByte[33];
	memset(strNumByte,0x00,33);
	string strSrc =itoa(iNumSrc,strNumByte,2);
	vector<char> vecNumByte(strSrc.c_str(),strSrc.c_str()+strSrc.length());
	bool bChange(false);
	if (vecNumByte.empty())
	{
		return false;
	}
	for(size_t sCurSize = vecNumByte.size() - 1;sCurSize > 0; sCurSize--)
	{
		if (vecNumByte[sCurSize] == '1' && vecNumByte[sCurSize - 1] == '0')
		{
			vecNumByte[sCurSize] = '0';
			vecNumByte[sCurSize - 1] = '1';
			bChange =  true;
			break;
		}
	}
	if (bChange == false)
	{
		vecNumByte.insert(vecNumByte.begin()+1,1,'0');
	}
	string strDst(vecNumByte.begin(),vecNumByte.end());
	iNumDst = strtol(strDst.c_str(),NULL,2);
	cout << "src:" << strSrc << "\ndst:" << strDst << endl;
	return true;
}

int main()
{
    int iIn = 88888;
	int iOut(0);
	GetNextByteNum(iIn,iOut);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值