Approach
I found that the answer for this is find the longest continuous 1’s in the number, and remove that 1. For instance, 1000111 -> 1000011.
I also found an interesting thing to do this without using while loop to shift, the formula for this is n & ~((~n & (n+1)) >> 1). The part (~n & (n+1)) >> 1 is the highest continuos 1 bit since for n = ? 0 1 .. 1, we have n+1 = ? 1 0 .. 0, then ~n & (n+1) = 0 1 0 .. 0, shifting this by one is the highest bit.
Code
class Solution {
public:
vector<int> minBitwiseArray(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n);
for(int i = 0 ; i < n ; ++i) {
int shift = -1;
int cur = nums[i];
while(cur & 1 == 1) {
cur >>= 1;
++shift;
}
if(shift == -1) {
ans[i] = -1;
} else {
ans[i] = (nums[i] ^ (1 << shift));
}
}
return ans;
}
};