题目描述
给你一个长度为 n 的 质数 数组 nums 。你的任务是返回一个长度为 n 的数组 ans ,对于每个下标 i ,以下 条件 均成立:
ans[i] OR (ans[i] + 1) == nums[i]
除此以外,你需要 最小化 结果数组里每一个 ans[i] 。
如果没法找到符合 条件 的 ans[i] ,那么 ans[i] = -1 。
质数 指的是一个大于 1 的自然数,且它只有 1 和自己两个因数。
x|(x+1)一定为奇数。OR 是按位或运算。
方法一:
解题思路:
首先,将每一个 num 转换为二进制形式。我们这里用一个数组来存储。通过遍历这个数组来实现查找从右边数第一个 0 右边的 1,再将它变为 0。
举例:5[101]->4[100],因为(4)|(4+1)=[100]|[101]->[101]
7[111]->3[11],因为(3)|(3+1)=[11]|[100]->[111]
11[1011]->9[1001],因为(9)|(9+1)=[1001]|[1010]->[1011]
规律就是这样。如果全是 1 就把最高位的 1 变为 0,如果末尾是 0,说明它是一个偶数。
完整代码
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> minBitwiseArray(vector<int> &nums) {
vector<int> ans;
for (int num : nums) {
// 2 是特殊情况 (偶数)
if (num == 2) {
ans.push_back(-1);
continue;
}
vector<int> bits;
int x = num;
// 将 num 转换为二进制位
(x > ) {
bits.(bits.(), x % );
x /= ;
}
res = ;
j = bits.() - ;
(j >= ) {
(bits[j] == && j != ) {
j--;
}
(bits[j] == && j != bits.() - ) {
bits[j + ] = ;
temp = ;
( bit : bits) {
temp = temp * + bit;
}
res = temp;
;
}
(bits[j] == && j == ) {
bits[j] = ;
temp = ;
( bit : bits) {
temp = temp * + bit;
}
res = temp;
;
}
}
ans.(res);
}
ans;
}
};


