状态转移 凳子一个挨着一个放着 位运算 翻转数位 动态规划 32位中,怎么判断某一位为1:位运算中的且运算

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func reverseBits(num int) int {
    // a : 当前位置累计连续1的个数,遇到0为0
    // b:  当前位置可以构成连续的1的个数
    // 遇到0 状态转移
    a, b, ans := 0, 0, 0
    for i := 0; i < 32; i++ {
        if num&(1<<i) == 0 {
            b = a + 1
            a = 0
        } else {
            a++
            b++
        }
        if b > ans {
            ans = b
        }
    }
    return ans
}

  

 

You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of 1s you could create.

Example 1:

Input: num = 1775(110111011112)
Output: 8
Example 2:

Input: num = 7(01112)
Output: 4

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-bits-lcci 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func reverseBits(num int) int {
    // 补一个洞,使得连续的元素最多 :
    // 反转 即 “补洞” :
    // 凳子一个挨着一个放着,现在搬走了若干个凳子,在空出的位置中在选一个位置,放入一个凳子,使得挨着的凳子最多
    start, ans, first := 0, -1, false
    nextStart := -1
    for c := 0; c < 32; c++ {
        // 位为0 状态转移
        // 注意:运算法优先级 & 高于 <<
        if num&(1<<c) == 0 {
            // 这是一个空位,可以放入凳子
            if !first { // 第一个空位
                first = true
            } else {
                _ans := c - start // (c - 1) - start + 1
                if _ans > ans {
                    ans = _ans
                }
                //  状态转移
                start = nextStart
            }
            nextStart = c + 1
        }
    }
    _ans := 31 - start + 1
    if _ans > ans {
        ans = _ans
    }
    if start == 0 {
        ans = 32
    }
    return ans
    // 32位中,怎么判断某一位为1:位运算中的且运算
}

  

posted @   papering  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-06-27 如何在Redis中实现事务
2020-06-27 Go Proverbs
2019-06-27 Uber如何搭建一个基于Kafka的跨数据中心复制平台 原创: 徐宏亮 AI前线 今天
2019-06-27 a
2018-06-27 Why Do Microservices Need an API Gateway?
2018-06-27 在视频合成中加入背景音乐的处理 混音
2018-06-27 Speech Recognition Grammar Specification Version 1.0 JavaScript TTS 文本发音
点击右上角即可分享
微信分享提示