How to add two numb…
 
Notifications
Clear all

How to add two numbers without using the plus operator in Java?

1 Posts
2 Users
0 Likes
378 Views
0
Topic starter

How to add two numbers without using the plus operator in Java?

1 Answer
0

To add two numbers without using the plus operator in Java, you can use the concept of bitwise operations and arithmetic.

Here’s an example of how you can achieve this using bitwise operations:

 

public class AddNumbersWithoutPlusOperator {
    public static int addNumbers(int a, int b) {
        while (b != 0) {
            int carry = a & b; // Calculate the carry
            a = a ^ b; // Add the numbers without considering the carry
            b = carry << 1; // Left shift the carry to add to the next bit
        }
        return a;
    }

    public static void main(String[] args) {
        int num1 = 7;
        int num2 = 5;
        int sum = addNumbers(num1, num2);
        System.out.println("Sum: " + sum);
    }
}
Share: