Problem Statement
Given an integer n
, write a program to:
- Multiply the number by
2
using bitwise operations. - Divide the number by
2
using bitwise operations.
You are not allowed to use the *
(multiplication) or /
(division) operations.
Examples
Example 1:
Input: n = 5
Output: 10, 2
Explanation:
1 Multiplying 5 by 2 yield 10
2 Dividing 5 by 2 yield 2 (integer division)
Different Approaches
1️⃣ Bit Manipulation
Intuition:
The binary representation of a number gives us a powerful way to manipulate it using bitwise operations:
- Left Shift (
<<
): Shifting all bits to the left by one position effectively multiplies the number by 2. Each bit is moved to the next higher place value. - Right Shift (
>>
): Shifting all bits to the right by one position effectively divides the number by 2, discarding the least significant bit. This is equivalent to integer division.
These operations are faster than arithmetic multiplication and division because they directly manipulate the binary representation at the hardware level.
Approach:
- Multiplication by 2:
- Use the left shift operator (
<<
) to multiply the number by2
. - Shifting left moves each bit one place to the left, effectively doubling the number.
- Use the left shift operator (
- Division by 2:
- Use the right shift operator (
>>
) to divide the number by2
. - Shifting right moves each bit one place to the right, effectively halving the number (with integer division).
- Use the right shift operator (
- Handle edge cases:
- For
n = 0
, both multiplication and division yield0
. - For negative numbers, the bit shifts account for the sign bit correctly.
- For
Code:
#include <iostream>
using namespace std;
void multiplyAndDivideByTwo(int n) {
// Multiply by 2 using left shift
int multiplied = n << 1;
// Divide by 2 using right shift
int divided = n >> 1;
// Output the results
cout << "Input: " << n << endl;
cout << "Multiplied by 2: " << multiplied << endl;
cout << "Divided by 2: " << divided << endl;
}
int main() {
int number = 5; // Example input
multiplyAndDivideByTwo(number);
return 0;
}
Complexity Analysis:
- Time Complexity:
O(1)
- Space Complexity:
O(1)