“人生得一知己足矣,斯世当以同怀视之。”——鲁迅
题目
给你两个整数 n
和 x
。你需要构造一个长度为 n
的 正整数 数组 nums
,对于所有 0 <= i < n - 1
,满足 nums[i + 1]
大于 nums[i]
,并且数组 nums
中所有元素的按位 AND
运算结果为 x
。
返回 nums[n - 1]
可能的 最小 值。
难度:中等
分析
此题的思路不算很难想到,重要的是有位运算的思想,笔者在此标记一下该题。
首先明确x一定是数组的第一个数,此题要求数组 nums
中所有元素的按位 AND
运算结果为 x
,因此x二进制位中为1的地方所有的数都应该为1,而对于x二进制位为0的地方,由于x参与AND运算,结果一定为0,所以其他数为0或1皆可。综上,我们能改变的是x二进制位为0的部分,由于数组要求递增,我们可以知道要增加n-1,所以我们将n-1的二进制“嵌入”x二进制为0的部分。
解答1和解答2方法相同,解答2优化了一些,运算耗时较短。
解答
解答1
class Solution {
public:
long long minEnd(int n, int x) {
long long ans=0;
int add=n-1;
int count=0;
while (add&&x){
int index1=x&1;
x>>=1;
if (index1){
ans|=((long long)1<<count);
}else{
int index2=add&1;
add>>=1;
if (index2){
ans|=((long long)1<<count);
}
}
count++;
}
while (add){
if (add&1){
ans|=((long long)1<<count);
}
add>>=1;
count++;
}
while (x){
if (x&1){
ans|=((long long)1<<count);
}
x>>=1;
count++;
}
return ans;
}
};
解答2
class Solution {
public:
long long minEnd(int n, int x) {
long long ans=x;
int add=n-1;
int count=0;
while (add){
if (((ans>>count)&1)==0){
//将add二进制位嵌入
if (add&1){
ans|=((long long)1<<count);
}
add>>=1;
}
count++;
}
return ans;
}
};