题目很简单,就是求一个十进制数的二进制形式中,相邻两个一之间的最大距离
方法一:最一般方法,把十进制数变成二进制的字符串,而后遍历一下即可,beat 4%
python
class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
N = str(bin(N))[2:]
print(N)
res = 0
count = 0
flag = 0
for i in range(len(N)):
if N[i] == '1' and flag == 0:
flag = 1
count = 1
elif N[i] == '0' and flag == 1:
count += 1
elif N[i] == '1' and flag == 1:
res = max(res, count)
count = 1
else:
pass
return res
上述代码比较臃肿,优化了一下,减少了不比要的标志位和判断,beat 34%
class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
N = str(bin(N))[2:]
res = 0
count = 0
for i in range(len(N)):
if N[i] == '0':
count += 1
elif N[i] == '1':
res = max(res, count)
count = 1
return res
Java
class Solution {
public int binaryGap(int N) {
String Nbin = Integer.toBinaryString(N);
char[] Nstr = Nbin.toCharArray();
int count = 0;
int res = 0;
for(int i=0;i<Nstr.length;i++){
if(Nstr[i]=='1') {
res = Math.max(res,count);
count = 1;
}
else{
count+=1;
}
}
return res;
}
}
方法二: 利用移位操作,能mod 2说明末尾为0,右移一位,用一个flag记录是否之前已经遇到过1,过遇到过那么遇到0时就计数器+1,如果没有则不操作;如果 mod 21,说明当前的末尾数字是一,每次遇到1都要从头来过,如果flag 为1,取计数器和res的最大值,flag0说明至今没有遇到过1,则让flag=1
class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
flag = False
res = 0
count = 1
while N:
if N % 2 ==0:
N >>=1
if flag:
count +=1
else:
N -=1
N >>=1
if flag:
res = max(res,count)
count =1
else:
flag =True
return res
###做这道题时发现了一个有意思的现象,就是用while(N) 的时候只beat了8%,用while N 的时候却beat了94%,个人认为是括号处理的话把N当做一个代码块来处理了(python)
Java
class Solution {
public int binaryGap(int N) {
int res = 0;
int count = 0;
boolean flag = false;
while(N>0){
if(N % 2 ==1){
flag =true;
N >>=1;
res = Math.max(res,count);
count =1;
}
else {
N >>=1;
if (flag)
count +=1;
}
}
return res;
}
}