BinaryGap

Find longest sequence of zeros in binary representation of an integer.

binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

int solution(int N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [1..2,147,483,647].

解决思路:

  1. 写一个十进制转化成二进制
  2. 把二进制所有的 ‘1’ 标注位置存到一个数组中
  3. 通过1的位置计算最大‘0’的间隔
  4. 通过最大值2,147,483,647()得到需要31位二进制。
/**  
 * @author twodog
 * programming language:java
 */ 
public class BinaryGap {
	
	public static void  main(String [] args) {
		BinaryGap binaryGap =new BinaryGap();
		System.out.println(binaryGap.solution(529));//输入数字得出结果	
	}
	//十进制转换二进制倒序输出
	public int[] tT2(int N) {
		int d=0;//定义二进制数组中每位的数字
		int dividend=1;//二进制中每一级的被除数
		int a[]=new int[31];//定义二进制输出倒序数组
		for(int i=0;dividend!=0;i++) {
			d=N%2;
			dividend=N/2;
			N=dividend;
			a[i]=d;	
		}
		return a;
	}
	//计算最大0间隔的数量
public int solution(int N) {
	int binary[]=new int[31];
	int one[]=new int[31];//二进制中数字‘1’的位置
	binary=tT2(N);
	int count=0;
	int sumzeros=0;//定义最大连续‘0’的个数
	for (int i = 0; i < binary.length; i++) {
		if( binary[i]==1)
			one[count++]=i;
	}
	for (int i = 0; i < one.length-1; i++) {
		if(one[i+1]-one[i]-1>sumzeros)
		sumzeros=one[i+1]-one[i]-1;
	}
	return sumzeros;
}
}