Reverse Bits LCCI

Problem description

https://leetcode-cn.com/problems/reverse-bits-lcci/

Solution

用一个长度为 1000 的数组记录该数组内连续1的长度,最终通过计算 该数组相邻元素的最大值。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
fun reverseBits(num: Int): Int {
var n = num
val res = IntArray(1000)
var index = 0
var max = 0
while (n > 0) {
if (n and 1 == 1)
res[index]++
else
index++
n = n shr 1
}

for (i in 0..index) {
if (max < res[i] + res[i + 1] + 1)
max = res[i] + res[i + 1] + 1
}
return max
}
}
文章目录
  1. 1. Problem description
  2. 2. https://leetcode-cn.com/problems/reverse-bits-lcci/
  3. 3. Solution
  4. 4. Code
|