[LeetCode] Guess the Number Using Bitwise Questions I

3064. Guess the Number Using Bitwise Questions I

There is a number n that you have to find.

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.

Return the number n.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** 
* Definition of commonSetBits API.
* int commonSetBits(int num);
*/

class Solution {
public:
int findNumber() {
int res = 0, bit = 1;
for(int i = 0; i < 32; i++) {
if(commonSetBits(bit)) res |= bit;
bit<<=1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/10/PS/LeetCode/guess-the-number-using-bitwise-questions-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.