Add Two Numbers Without + Operator

Add Two Numbers Without + Operator

Hard C++ Operators 29 views
Explanation Complexity

Problem Statement

Add two numbers using only bitwise operators.
Real Life: Understanding how CPU does addition internally.

Input Format

Two integers a and b.

Output Format

Sum of the two numbers.

Example

5 7 
12

Constraints

• Integers

• Do not use + or - operators

• Use bitwise operators only

Concept Explanation

The CPU adds numbers using bitwise logic, not directly with +.
Addition can be broken into two parts:

• Sum without carry

• Carry calculation

Step-by-Step Explanation

1.Use XOR (^) to calculate sum without carry.

2.Use AND (&) and left shift to calculate carry.

3.Repeat the process until there is no carry left.

4.Final result is the sum.

Concept Explanation

The CPU adds numbers using bitwise logic, not directly with +.
Addition can be broken into two parts:

• Sum without carry

• Carry calculation

Step-by-Step Explanation

1.Use XOR (^) to calculate sum without carry.

2.Use AND (&) and left shift to calculate carry.

3.Repeat the process until there is no carry left.

4.Final result is the sum.

Input / Output Format

Input Format
Two integers a and b.
Output Format
Sum of the two numbers.
Constraints
• Integers

• Do not use + or - operators

• Use bitwise operators only

Examples

Input:
5 7
Output:
12

Example Solution (Public)

C++
void operator_q15_add_without_plus() {
    int a = 15;
    int b = 27;
    
    cout << "Adding " << a << " and " << b << " without + operator" << endl;
    
    while(b != 0) {
        int carry = a & b;      // Find carry bits
        a = a ^ b;              // Sum without carry
        b = carry << 1;         // Shift carry left
    }
    
    cout << "Result: " << a << endl;
}

Official Solution Code

void operator_q15_add_without_plus() {
    int a = 15;
    int b = 27;
    
    cout << "Adding " << a << " and " << b << " without + operator" << endl;
    
    while(b != 0) {
        int carry = a & b;      // Find carry bits
        a = a ^ b;              // Sum without carry
        b = carry << 1;         // Shift carry left
    }
    
    cout << "Result: " << a << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.