There is also a pre-defined API int commonSetBits(int num), which returns the number of bits where both n and num are 1 in that position of their binary representation. In other words, it returns the number of set bits in n & num, where & is the bitwise AND operator.
We can reconstruct the hidden number n by querying each bit position individually. For each bit position, we query with a number that has only that bit set. If the result is 1, then that bit is set in n; otherwise, it is not. By repeating this for all 32 bits, we can reconstruct n.
classSolution {
public:int findNumber(ArrayReader &reader) {
int ans =0;
for (int i =0; i <32; ++i) {
if (reader.commonSetBits(1<< i)) {
ans |= (1<< i);
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
funcfindNumber(readerArrayReader) int {
ans:=0fori:=0; i < 32; i++ {
ifreader.commonSetBits(1<<i) ==1 {
ans|=1<<i }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintfindNumber(ArrayReader reader) {
int ans = 0;
for (int i = 0; i < 32; i++) {
if (reader.commonSetBits(1 << i) == 1) {
ans |= 1 << i;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindNumber(reader: ArrayReader): Int {
var ans = 0for (i in0 until 32) {
if (reader.commonSetBits(1 shl i) ==1) {
ans = ans or (1 shl i)
}
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
deffindNumber(self, reader: 'ArrayReader') -> int:
ans =0for i in range(32):
if reader.commonSetBits(1<< i) ==1:
ans |=1<< i
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnfind_number(reader: &mut ArrayReader) -> i32 {
letmut ans =0;
for i in0..32 {
if reader.common_set_bits(1<< i) ==1 {
ans |=1<< i;
}
}
ans
}
}