[CrackCode] 5.3 Print the next smallest and next largest number

Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation 

================

Analysis:

Assume that we are given 11010100110, if we want to find out the next larger number, we can 

1. from right to left, find out the first '1'. (11010100110)

2. after the first '1', find out the first '0'. (11010100110)

3. change this '0' to '1'. (11010101110)

4. change the '1' next to current digit to '0', equal to switch these 2 digits. (11010101010) 

5. move all the passed '1' (according to the requirement "the same number of 1 bits") to right most in order to find out the "next largest". (11010101001)


Similarly, for the next smallest number of 11010100110

1. find out the 1st '0'. (11010100110)

2. after the first '0', find the first '1'. (11010100110)

3. change this '1' to 0. (11010100100)

4 change the next to current digit to '1', equal to switch these 2 digits. (11010100101)

5. move all the passed '1' to left most in order to find out the "next smallest". (in this case, no '1' digit passed)

public class Answer {
	public static int nextNumber(int num){
		// find the 1st '1'
		int index = 0;
		int countOne = 0;
		
		while(!(((1<<index) & num)>0)) index++;
		
		// turn on next 0
		while(((1<<index)&num)>0) {
			index++;
			countOne++;
		}
		num = num|(1<<index);
		
		// turn off the next 1
		index--;
		num = ~(1<<index)&num
		countOne--;

		// move remaining 1 to right most
		// set 1
		for(int i=0; i<countOne; i++){
			num = (1<<i)|num;
		}
		// set 0
		for(int i=countOne; i<index; i++){
			num = ~(1<<i)&num
		}
		
		return num;
	}
	
	public static int prevNumber(int num){
		// find the 1st 0
		int index = 0;
		int countOne = 0;
		while(((1<<index)&num)>0) {
			index++;
			countOne++;
		}
		
		// turn off next 1
		while(!(((1<<index)&num)>0)) index++;
		num = ~(1<<index)&num
		
		// turn next digit to 1
		index--;
		num = (1<<index)|num;
		
		// move passed 1s to left most
		for(int i=index-1; i>=index-countOne;i--) num = (1<<i)|num; // set 1
		for(int i=0; i<index-countOne; i++) num = ~(1<<i)&num // set 0
		
		return num;
	}
	
	public static void main(String[] args) {
		int a = 27;
		System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a));
		int b = nextNumber(a);
		System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b));		
		int c = prevNumber(a);
		System.out.println(c + ": " + AssortedMethods.toFullBinaryString(c));	
	}

Note: set 1 at n digit, use (1<<n)|num; set 0 at n digit, use ~(1<<n)&num.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值