bitwise addition using '&' , '^' and '<<' operator

 import java.util.Scanner;


class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt();
        int b = in.nextInt();
        System.out.println(Integer.toBinaryString(a));
        System.out.println(Integer.toBinaryString(b));

        while (b != 0) {
            int carry = a & b;// first occurence of carry in bitwise operation
            System.out.println("c=  a&b carry --> " + Integer.toBinaryString(carry));

            a = a ^ b;// it actually perform addition and store in a, ignoring carry values
            System.out.println("a = a^b addition --> " + Integer.toBinaryString(a));
            b = carry << 1; /*
                             * left shifted so it will be added to next bit addition
                             * as next iteration a^b addition operation will happen
                             */
            System.out.println("b = c<<1 left shift --> " + Integer.toBinaryString(b));
        }

        System.out.println(Integer.toBinaryString(a));
    }
}

Comments