一.问题描述
给定一个正整数 N,找到并返回 N 的二进制表示中两个连续的 1 之间的最长距离。
如果没有两个连续的 1,返回 0 。
示例 1:
输入:22
输出:2
解释:
22 的二进制是 0b10110 。
在 22 的二进制表示中,有三个 1,组成两对连续的 1 。
第一对连续的 1 中,两个 1 之间的距离为 2 。
第二对连续的 1 中,两个 1 之间的距离为 1 。
答案取两个距离之中最大的,也就是 2 。
示例 2:
输入:5
输出:2
解释:
5 的二进制是 0b101 。
示例 3:
输入:6
输出:1
解释:
6 的二进制是 0b110 。
示例 4:
输入:8
输出:0
解释:
8 的二进制是 0b1000 。
在 8 的二进制表示中没有连续的 1,所以返回 0 。
提示:
1 <= N <= 10^9
Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
If there aren't two consecutive 1's, return 0.
Example 1:
Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.
Example 2:
Input: 5
Output: 2
Explanation:
5 in binary is 0b101.
Example 3:
Input: 6
Output: 1
Explanation:
6 in binary is 0b110.
Example 4:
Input: 8
Output: 0
Explanation:
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.
Note:
1 <= N <= 10^9
二.解题思路
变成二进制,然后记录相邻两个1的位置即可,一遍扫描就ok了
关键是如何变成二进制,直接调用库函数的话没有意义
首先直接想到的是每次/2,mod2==1就相当于有1
这种即使添加剪枝操作还是会超时,之后想到用位移操作
把一个数设置成1,每次位移i位然后与N相与,如果是1就说明这个位有1,然后和上次1的位置比较
主要是要注意一下边界的处理,数字只有1个1的情况,和第一个1的位置如何记录,gap如何计算
思路讲的比较清楚,代码就不注释了
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起讨论一起刷题一起ac
import math
class Solution:
def binaryGap(self, N: int) -> int:
if N == 0 | N == 1:
return 0
maxgap =-1
helper=1
gap=0
index_last=0;
t=0 # this is used to judge whether there is only one 1 in N and the update of gap
for i in range(0,36):
if (helper<<i)>N:
break
if (helper<<i)&N:
t=t+1
if t!=1: # pay attention to this step
gap=i-index_last
maxgap=max(gap,maxgap)
index_last=i
return maxgap
778

被折叠的 条评论
为什么被折叠?



