From f28c1f39226b57922b2ca3ad6fabd60c1e3b82ad Mon Sep 17 00:00:00 2001 From: Ravi Mandliya Date: Sat, 8 Apr 2017 23:33:39 -0700 Subject: [PATCH] Added a program to check if two integers are of opposite signs. --- README.md | 1 + bit_manipulation/check_opposite_signs.cpp | 35 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 bit_manipulation/check_opposite_signs.cpp diff --git a/README.md b/README.md index a4fccac..fadecec 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ Include contains single header implementation of data structures and some algori | Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n right bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.|[swapSetOfBits.cpp](bit_manipulation/swapSetOfBits.cpp)| | Add two numbers without using any arithmetic operators | [addition_without_operators.cpp](bit_manipulation/addition_without_operators.cpp)| |Louise and Richard play a game. They have a counter set to N. Louise gets the first turn and the turns alternate thereafter. In the game, they perform the following operations: The resultant value is the new N which is again used for subsequent operations.The game ends when the counter reduces to 1, i.e., N == 1, and the last person to make a valid move wins. |[counter_game.cpp](bit_manipulation/counter_game.cpp)| +|Determine if two integers are of opposite signs|[check_opposite_signs.cpp](bit_manipulation/check_opposite_signs.cpp)| ### Cracking the coding interview problems diff --git a/bit_manipulation/check_opposite_signs.cpp b/bit_manipulation/check_opposite_signs.cpp new file mode 100644 index 0000000..dc8c327 --- /dev/null +++ b/bit_manipulation/check_opposite_signs.cpp @@ -0,0 +1,35 @@ +/* + * Given two integers, using bit manipulations determine if they are of opposite signs. + * Most Significant Bit (MSB) of number represents sign of the number. If it is 1, it represents + * a negative value, if it is 0, it represents a positive value. + * If MSB of two numbers are different, their XOR would be 1, otherwise it would be 0. + * Thus, result of XOR of two numbers will have MSB 1 if they are of opposite signs, + * 0 other wise, in other words, XOR of two numbers would be negative (MSB 1) if they are of + * opposite signs. + * Source : http://graphics.stanford.edu/~seander/bithacks.html + */ + +#include + + bool are_of_different_signs(int a, int b) + { + return ((a ^ b) < 0); + } + + int main() + { + int a, b; + std::cout << "Enter number 1: "; + std::cin >> a; + std::cout << "Enter number 2:"; + std::cin >> b; + if (are_of_different_signs(a, b)) + { + std::cout << a << " and " << b << " are of different signs" << std::endl; + } + else + { + std::cout << a << " and " << b << " are of same signs" << std::endl; + } + return 0; + } \ No newline at end of file