下一个数(Leetcode 程序员面试金典05.04)

1

题目分析

   题目一看就是位运算来求解,小伙伴们看一看能找到什么规律。

位运算

这个题目可以看成两个问题,一个是找到比它大的最小的数,一个是比它小的最大的数。

1

因此这个问题变成了找第一个1后面出现的第一个0和第一个0后面出现的第一个1

算法的**时间复杂度为$O(log(n))$,空间复杂度为$O(1)$**。

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
vector<int> findClosedNumbers(int num) {
if (num == INT32_MAX) return { -1, -1 };
int findOne = 1, findZero = 1;
vector<int> res(2, num);

int cntOne = -1;
while (!(num & findOne)) {
findOne <<= 1;
}
while (findOne != INT32_MIN && num & findOne) {
res[0] ^= findOne;
cntOne++;
findOne <<= 1;
}
res[0] |= findOne;
if (findOne == INT32_MIN) { res[0] = -1; }
else {
findOne = 1;
while (cntOne--) {
res[0] |= findOne;
findOne <<= 1;
}
}

cntOne = 0;
while (num & findZero) {
cntOne++;
res[1] ^= findZero;
findZero <<= 1;
}
while (findZero != INT32_MIN && !(num & findZero)) {
findZero <<= 1;
}
if (findZero == INT32_MIN) { res[1] = -1; }
else {
res[1] = (res[1] | (findZero >> 1)) ^ findZero;
findZero >>= 2;
while (cntOne--) {
res[1] |= findZero;
findZero >>= 1;
}
}
return res;
}
};

刷题总结

  这个题目是一个难度较大的位运算,其中不仅仅包含了位运算的知识,还牵扯了许多数学的知识进去,而且还用到了一些贪心的思想,小伙伴们遇到这样的题目,可以先找一找规律,举两个例子,这样解题思路可能就会冒出来了。

-------------本文结束感谢您的阅读-------------
0%