How to add two integers without using arithmetic operators in Java

1 Answer

0 votes
public class MyClass {
    public static int Add(int x, int y) { 
        while (y != 0) { 
            int carry = x & y;  
            System.out.println("carry = x & y = " + carry);  
       
            x = x ^ y;  
            System.out.println("x = x ^ y = " + x);  
             
            y = carry << 1; 
            System.out.println("y = carry << 1 = " + y);  
        } 
        return x; 
    } 
    public static void main(String args[]) {
        System.out.println(Add(8779, 19));
    }
}




/*
run:

carry = x & y = 3
x = x ^ y = 8792
y = carry << 1 = 6
carry = x & y = 0
x = x ^ y = 8798
y = carry << 1 = 0
8798

*/

 



answered Aug 12, 2021 by avibootz
...