Sum of two numbers with bitwise operator

后端 未结 3 1937
旧巷少年郎
旧巷少年郎 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:41

    I think that the optimizations should be in the field of readability, rather than performance (which will probably be handled by the compiler).

    Use for loop instead of while

    The idiom for (int i=0; i<32; i++) is more readable than the while loop if you know the number of iterations in advance.

    Divide the numbers by two

    Dividing the numbers by two and getting the modulu:

    n1 = p % 2;
    p  /= 2;
    

    Is perhaps more readable than:

    (p & (1<<(i-1)))>>(i-1);
    

提交回复
热议问题