Medium
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
You're given two integers, n and m. Find position of the rightmost bit in which they differ in their binary representations (it is guaranteed that such a bit exists), counting from right to left.
Return the value of 2^position_of_the_found_bit (0-based).
Example
-
For n = 11 and m = 13, the output should be
differentRightmostBit(n, m) = 2.11v10 = 1011v2, 13v10 = 1101v2, the rightmost bit in which they differ is the bit at position 1 (0-based) from the right in the binary representations.
So the answer is 2^1 = 2. -
For n = 7 and m = 23, the output should be
differentRightmostBit(n, m) = 16.7v10 = 111v2, 23v10 = 10111v2, i.e.
- 00111
10111
So the answer is 2^4 = 16.
Input/Output
-
[execution time limit] 0.5 seconds (cpp)
-
[input] integer n
Guaranteed constraints:
0 ≤ n ≤ 2^30. -
[input] integer m
Guaranteed constraints:
0 ≤ m ≤ 2^30,
n ≠ m. -
[output] integer
[C++] Syntax Tips
// Prints help message to the console
// Returns a string
std::string helloWorld(std::string name) {
std::cout << "This prints to the console when you Run Tests" << std::endl;
return "Hello, " + name;
}
Solution
int differentRightmostBit(int n, int m) {
return (n^m)&-(n^m);
}
'Codesignal' 카테고리의 다른 글
<Codesignal> Is Unstable Pair? (0) | 2020.06.26 |
---|---|
<Codesignal> Equal Pair of Bits (0) | 2020.06.17 |
<Codesignal> Swap Adjacent Bits (0) | 2020.06.16 |
<Codesignal> Stolen Lunch (0) | 2020.05.29 |
<Codesignal> Cipher 26 (0) | 2020.05.29 |