Codility Lessons -Lesson 1 Iterations

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;
}
}

 

全部评论

相关推荐

点赞 评论 收藏
分享
Twilight_m...:表格简历有点难绷。说说个人看法: 1.个人基本情况里好多无意义信息,什么婚姻状况、健康状况、兴趣爱好、户口所在地、身份证号码、邮政编码,不知道的以为你填什么申请表呢。 2.校内实践个人认为对找工作几乎没帮助,建议换成和测开有关的项目,实在没得写留着也行。 3.工作经历完全看不出来是干什么的,起码看着和计算机没啥关系,建议加强描述,写点你在工作期间的实际产出、解决了什么问题。 4.个人简述大而空,看着像AI生成,感觉问题最大。“Python,C,C++成为我打造高效稳定服务的得力工具”、“我渴望凭借自身技术知识与创新能力,推动人工智能技术的应用发展,助力社会实现智能化转型”有种小学作文的美感。而且你确定你个人简述里写的你都会嘛?你AI这块写的什么“深入研究”,发几篇顶会的硕博生都不一定敢这么写。而且你AI这块的能力和软测也完全无关啊。个人简述建议写你对哪些技术栈、哪些语言、哪些生产工具的掌握,写的有条理些,而且最好是和测开强相关的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务