保持二进制中1的个数相同,求大于输入自然数的最小数

7 篇文章 0 订阅
Problem Statement
    
The binary weight of a positive integer is the number of 1's in its binary representation. For example, the decimal number 1 has a binary weight of 1, and the decimal number 1717 (which is 11010110101 in binary) has a binary weight of 7.
Given a positive integer N, return the smallest integer greater than N that has the same binary weight as N.
Definition
    
Class:
NextNumber
Method:
getNextNumber
Parameters:
int
Returns:
int
Method signature:
int getNextNumber(int N)
(be sure your method is public)
    


Notes
-
The result is guaranteed to fit in a signed 32-bit integer.
Constraints
-
N will be between 1 and 1,000,000,000, inclusive.
Examples
0)


    
1717
Returns: 1718
Example from the problem statement.
1)


    
4
Returns: 8
4 is 100 in its binary representation and weighs 1. The next number is 1000(in binary) which represents 8.
2)


    
7
Returns: 11
The decimal 7 is binary 111, so it has binary weight of 3. The next number with the same binary weight is 11, which is 1011 in binary.
3)


    
12
Returns: 17
12 in decimal is 1100 in binary. The next number with the same binary weight is 10001 in binary, which is 17.
4)


    
555555

Returns: 555557



using namespace std;

class NextNumber
{
public:
	int getNextNumber( int N )
	{
		int numOfOne = 0, shiftCount = 0;
		if( N <= 0 ) return -1;
		while(  true )
		{
			if( N & 1 )	numOfOne++;
			else if( numOfOne > 0 )
			{
				N++;
				numOfOne--;
				return (N << shiftCount) + (1 <<  numOfOne) - 1;
			}
			N = N >> 1;
			shiftCount++;
		}
	}
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值