状态转移 凳子一个挨着一个放着 位运算 翻转数位 动态规划 32位中,怎么判断某一位为1:位运算中的且运算
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
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:位运算中的且运算
}

浙公网安备 33010602011771号