Java&C++题解与拓展——leetcode868.二进制间距【模拟么的新知识】

每日一题做题记录,参考官方和三叶的题解

题目要求

image.png

思路:模拟

简单题就没有什么好说的模拟,找每一个 1 1 1算距离记录最大值即可。

从前向后遍历

数据范围是 1 0 9 10^9 109,转成二进制就是30位,就从前往后逐位遍历找 1 1 1

Java

class Solution {
    public int binaryGap(int n) {
        int res = 0;
        for(int i = 29, j = -1; i >= 0; i--) { // 逐位遍历
            if(((n >> i) & 1) == 1) { // 是1
                if(j != -1)  // 上一个1的位置
                    res = Math.max(res, j - i);
                j = i;
            }
        }
        return res;
    }
}
  • 时间复杂度: O ( log ⁡ n ) O(\log n) O(logn),遍历 n n n二进制的每一位
  • 空间复杂度: O ( 1 ) O(1) O(1)

C++

class Solution {
public:
    int binaryGap(int n) {
        int res = 0;
        for(int i = 29, j = -1; i >= 0; i--) {
            if(((n >> i) & 1) == 1) { // 是1
                if(j != -1) // 上一个1的位置
                    res = max(res, j - i);
                j = i;
            }
        }
        return res;
    }
};
  • 时间复杂度: O ( log ⁡ n ) O(\log n) O(logn),遍历 n n n二进制的每一位
  • 空间复杂度: O ( 1 ) O(1) O(1)

从后向前遍历

从末位开始取,逐位移动遍历,直至 n n n变为0。

Java

class Solution {
    public int binaryGap(int n) {
        int res = 0, pre = -1, i = 0;
        while(n > 0) {
            if((n & 1) == 1) { // 是1
                if(pre != -1)  // 上一个1的位置
                    res = Math.max(res, i - pre);
                pre = i;
            }
            n >>= 1;
            i += 1;
        }
        return res;
    }
}
  • 时间复杂度: O ( log ⁡ n ) O(\log n) O(logn),遍历 n n n二进制的每一位
  • 空间复杂度: O ( 1 ) O(1) O(1)

C++

class Solution {
public:
    int binaryGap(int n) {
        int res = 0, pre = -1, i = 0;
        while(n > 0) {
            if((n & 1) == 1) { // 是1
                if(pre != -1)  // 上一个1的位置
                    res = max(res, i - pre);
                pre = i;
            }
            n >>= 1;
            i += 1;
        }
        return res;
    }
};
  • 时间复杂度: O ( log ⁡ n ) O(\log n) O(logn),遍历 n n n二进制的每一位
  • 空间复杂度: O ( 1 ) O(1) O(1)

总结

简单模拟题,光速解决,两种语言代码也基本没区别。

刚好可以去还了昨天的债,昨天的凸包还没有学好,太浪了太浪了……


欢迎指正与讨论!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值