diff --git a/README.md b/README.md index 200a830..2690a0d 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ | Current Status| Stats | | :------------: | :----------: | -| Total Problems | 139 | -| Current Streak | 3 days | +| Total Problems | 140 | +| Current Streak | 4 days | | Longest Streak | 91 ( August 17, 2015 - November 15, 2015 ) | @@ -70,7 +70,8 @@ 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)| +|Determine if two integers are of opposite signs.|[check_opposite_signs.cpp](bit_manipulation/check_opposite_signs.cpp)| +|Swap two bits at position p and q of a given integer.| [swapBits.cpp](bit_manipulation/swapBits.cpp)| ### Cracking the coding interview problems diff --git a/bit_manipulation/swapBits.cpp b/bit_manipulation/swapBits.cpp new file mode 100644 index 0000000..f5fe598 --- /dev/null +++ b/bit_manipulation/swapBits.cpp @@ -0,0 +1,39 @@ +#include +#include + +int swapBits(int n, int p, int q) +{ + if (p == q) + { + return n; + } + // If bits are same, no point swapping. + // Determine if bits are different + // + if (((n & (1 << p)) >> p) ^ ((n & (1 << q)) >> q)) + { + // toggle bits at p and q positions + // + n ^= (1 << p); + n ^= (1 << q); + } + + return n; +} + +int main() +{ + int n, p, q; + std::cout << "Enter a number: "; + std::cin >> n; + std::cout << "Enter bit position 1:"; + std::cin >> p; + std::cout << "Enter bit position 2:"; + std::cin >> q; + int r = swapBits(n, p, q); + std::cout << "Number before swap :" << n << " (" << std::bitset<8>(n).to_string() << ") " + << std::endl << "Number after swapping bits at position " + << p << " and " << q << " : " << r << " (" << std::bitset<8>(r) << ")" + << std::endl; + return 0; +} \ No newline at end of file