leetcode 868. 二进制间距 Binary Gap 解法 python

部署运行你感兴趣的模型镜像

一.问题描述

给定一个正整数 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

 

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值