MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Left Shift and Right Shift with Explanation

C++ Medium Operators 33 views
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.
Back to Questions

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

Input:
10
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).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next