comments | difficulty | edit_url | rating | source | tags | |
---|---|---|---|---|---|---|
true |
Medium |
1934 |
Weekly Contest 395 Q3 |
|
You are given two integers n
and x
. You have to construct an array of positive integers nums
of size n
where for every 0 <= i < n - 1
, nums[i + 1]
is greater than nums[i]
, and the result of the bitwise AND
operation between all elements of nums
is x
.
Return the minimum possible value of nums[n - 1]
.
Example 1:
Input: n = 3, x = 4
Output: 6
Explanation:
nums
can be [4,5,6]
and its last element is 6.
Example 2:
Input: n = 2, x = 7
Output: 15
Explanation:
nums
can be [7,15]
and its last element is 15.
Constraints:
1 <= n, x <= 108
According to the problem description, to make the last element of the array as small as possible and the bitwise AND result of the elements in the array is
Assume the binary representation of
If we ignore the underlined part, then the array sequence is
Therefore, the answer is to fill each bit of the binary of
The time complexity is
class Solution:
def minEnd(self, n: int, x: int) -> int:
n -= 1
ans = x
for i in range(31):
if x >> i & 1 ^ 1:
ans |= (n & 1) << i
n >>= 1
ans |= n << 31
return ans
class Solution {
public long minEnd(int n, int x) {
--n;
long ans = x;
for (int i = 0; i < 31; ++i) {
if ((x >> i & 1) == 0) {
ans |= (n & 1) << i;
n >>= 1;
}
}
ans |= (long) n << 31;
return ans;
}
}
class Solution {
public:
long long minEnd(int n, int x) {
--n;
long long ans = x;
for (int i = 0; i < 31; ++i) {
if (x >> i & 1 ^ 1) {
ans |= (n & 1) << i;
n >>= 1;
}
}
ans |= (1LL * n) << 31;
return ans;
}
};
func minEnd(n int, x int) (ans int64) {
n--
ans = int64(x)
for i := 0; i < 31; i++ {
if x>>i&1 == 0 {
ans |= int64((n & 1) << i)
n >>= 1
}
}
ans |= int64(n) << 31
return
}
function minEnd(n: number, x: number): number {
--n;
let ans: bigint = BigInt(x);
for (let i = 0; i < 31; ++i) {
if (((x >> i) & 1) ^ 1) {
ans |= BigInt(n & 1) << BigInt(i);
n >>= 1;
}
}
ans |= BigInt(n) << BigInt(31);
return Number(ans);
}