码迷,mamicode.com
首页 > 其他好文 > 详细

An easy problem(位运算)

时间:2019-08-13 13:42:30      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:tor   clu   you   图片   ber   names   main   this   ace   

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

技术图片

 

#include<iostream>
using namespace std;

int count(int n)
{
	int res=0;
	while(n)
	{
		res++;
		n=n&(n-1);
	}
	return res;	
}

int main()
{
	int n;
	while(cin>>n && n)
	{
		int cnt=count(n);
		while(n++)//自增
		{
			if(cnt==count(n))
			{
				cout<<n<<endl;
				break;
			}
		}
	}
	return 0;
}

  

 

An easy problem(位运算)

标签:tor   clu   you   图片   ber   names   main   this   ace   

原文地址:https://www.cnblogs.com/dragondragon/p/11345232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!