C++ Program to Left Shift and Right Shift with Explanation
C++
Medium
Operators
33 views
1 min read
156 words
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around shift, right, left. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Shift bits left or right to multiply/divide by 2.
Real Life: Fast multiplication/division by powers of 2.
Input Format
An integer N.
Output Format
Result after:
• Left shift (multiply by 2)
• Right shift (divide by 2)
Constraints
• Integer value
• Right shift on negative numbers is implementation-defined
Concept Explanation
Bit shifting moves bits left or right:
• Left shift (> 1) divides the number by 2.
This is faster than normal multiplication/division.
Step-by-Step Logic
1.Take input number N.
2.Left shift by 1 bit:
• N > 1 → divide by 2.
4.Print both results.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
void operator_q7_bit_shift() {
int num = 5; // Binary: 101
cout << "Original number: " << num << endl;
cout << "Left shift by 1 (num << 1): " << (num << 1) << endl; // 10 (multiply by 2)
cout << "Left shift by 2 (num << 2): " << (num << 2) << endl; // 20 (multiply by 4)
cout << "Right shift by 1 (num >> 1): " << (num >> 1) << endl; // 2 (divide by 2)
}
Output Example
Output:
After left shift = 20
After right shift = 5
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Shift bits left or right to multiply/divide by 2.
Real Life: Fast multiplication/division by powers of 2.
Input / Output
Output
Result after:
• Left shift (multiply by 2)
• Right shift (divide by 2)
Constraints
• Integer value
• Right shift on negative numbers is implementation-defined
Examples
Output:
After left shift = 20
After right shift = 5
Explanation
Concept Explanation
Bit shifting moves bits left or right:
• Left shift (> 1) divides the number by 2.
This is faster than normal multiplication/division.
Step-by-Step Explanation
1.Take input number N.
2.Left shift by 1 bit:
• N > 1 → divide by 2.
4.Print both results.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
void operator_q7_bit_shift() {
int num = 5; // Binary: 101
cout << "Original number: " << num << endl;
cout << "Left shift by 1 (num << 1): " << (num << 1) << endl; // 10 (multiply by 2)
cout << "Left shift by 2 (num << 2): " << (num << 2) << endl; // 20 (multiply by 4)
cout << "Right shift by 1 (num >> 1): " << (num >> 1) << endl; // 2 (divide by 2)
}
Solutions (0)
No solutions submitted yet. Be the first!