栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

文章目录
  • 题目要求
  • 思路:模拟
    • 从前向后遍历
      • Java
      • C++
    • 从后向前遍历
      • Java
      • C++
  • 总结

题目要求

思路:模拟

简单题就没有什么好说的模拟,找每一个 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)
总结

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

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


欢迎指正与讨论!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号