Codility---BinaryGap
A 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.
Write a function:
class Solution { public 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.
Assume that:
- N is an integer within the range [1..2,147,483,647].
Complexity:
- expected worst-case time complexity is O(log(N));
- expected worst-case space complexity is O(1).
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int N) {
// write your code in Java SE 8
int longest=0,temp=0;
int test = N;
boolean power = false;
if(test % 2 == 0){
test = test / 2;
power = true;
}
while(test !=0) {
if(test % 2 ==0) {
if(power) {
test = test / 2;
continue;
}
temp++;
} else {
temp = 0;
power =false;
}
test = test / 2;
if(longest < temp)
longest = temp;
}
return longest;
}
}
最新文章
- WWW读取安卓外部音乐文件
- -bash: /bin/rm: Argument list too long
- Hibernate4.1之后关于占位符的问题
- linux下定时重启tomcat
- SQL疑难杂症【4 】大量数据查询的时候避免子查询
- [0x01 用Python讲解数据结构与算法] 关于数据结构和算法还有编程
- javascript --- 词法分析
- js 返回并刷新
- 小心指针被delete两次
- jQuery插件之-Poshy Tip
- PHP 单态设计模式复习
- iOS用户行为追踪——无侵入埋点
- alpha冲刺总结随笔
- [转]恕我直言,在座的各位根本不会写 Java!
- python操作haproxy.cfg文件
- [Unity算法]弧度和角度
- Hdu4687 Boke and Tsukkomi
- Sql server 索引详解
- 1.1环境的准备(一)之Python解释器的安装
- RLP(转发注明出处)
热门文章
- 一款有意思的 Qt 飞行仪表控件
- Android 平台下Cordova 调用Activity插件开发
- vue 百度地图
- 简单IO,将一段字符串存入一个记事本
- QList介绍(QList比QVector更快,这是由它们在内存中的存储方式决定的。QStringList是在QList的基础上针对字符串提供额外的函数。at()操作比操作符[]更快,因为它不需要深度复制)非常实用
- Windows DPI Awareness for WPF
- Microsoft IoT Starter Kit
- c#调用ffmpeg嵌入srt/ass字幕提示Unable to open xxx.srt......
- OpenCV中基于HOG特征的行人检测
- Qt程序调试之Q_ASSERT断言(条件为真则跳过,否则直接异常+崩溃)