Sum of two numbers with bitwise operator

后端 未结 3 1981
旧巷少年郎
旧巷少年郎 2021-02-03 15:07

I am pasting the code to find the sum of two numbers with bitwise operator. Please suggest if it can be optimized. Thanks...

public static int getSum(int p, int          


        
3条回答
  •  轮回少年
    2021-02-03 15:42

    I think below soln is easy to understand & simple,

    public static void sumOfTwoNumberUsingBinaryOperation(int a,int b)
    {
        int c = a&b;
        int r = a|b;
        while(c!=0)
        {
            r =r <<1;
            c = c >>1;      
        }
        System.out.println("Result:\t" + r);    
    }
    

提交回复
热议问题