Left Shift and Right Shift

Left Shift and Right Shift

Medium C++ Operators 34 views
Explanation Complexity

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)

Example

10
After left shift  = 20
After right shift = 5

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 Explanation

1.Take input number N.

2.Left shift by 1 bit:

• N > 1 → divide by 2.

4.Print both results.

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.

Input / Output Format

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

Examples

Input:
10
Output:
After left shift = 20 After right shift = 5

Example Solution (Public)

C++
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)
}

Official Solution Code

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)
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.