问题描述:
Given a positive integer n, find and return the longest distance between any two adjacent 1’s in the binary representation of n. If there are no two adjacent 1’s, return 0. 找最远的两个1的距离
思路:
把n转化成二进制字符串,然后用双指针做,可以有O(N)时间复杂度:
代码如下:
class Solution {
public int binaryGap(int n) {
String a=Integer.toBinaryString(n);
int slower=0; //the MSB must be 1
int faster=1;
int max=0;
for(;faster<a.length();faster++){
if(a.charAt(faster)=='1'){
max=Math.max(max, faster-slower);
slower=faster;
}
}
return max;
}
}
可以用移位的方法做
思路: 我们需要两个变量负责记录工作:一个用来记是第几位,另一个用来记最新一个1在哪里。初始时,position变量为0,lastOne变量为-1(因为初始状态下我们认为尚未发现1)。n>0 判断是否完成逐位查看,(n&1)==1判断最低位是否为1,n=n>>1负责向右移位
代码如下:
class Solution {
public int binaryGap(int n) {
int position=0;
int lastOne=-1;
int dis=0;
while(n>0){
if((n&1)==1){
if(lastOne==-1) lastOne=position;
else{
dis=Math.max(dis, position-lastOne);
lastOne=position;
}
}
n=n>>1;
position++;
}
return dis;
}
}