Leetcode 868: Binary Gap

该博客介绍了如何找到一个正整数二进制表示中两个相邻1之间的最大距离。提供了两种解决方案:一种是将整数转换为二进制字符串并使用双指针方法;另一种是通过位运算进行逐位检查。这两种方法的时间复杂度均为O(N),其中N为二进制字符串的长度。
摘要由CSDN通过智能技术生成

问题描述:
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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值