Change sign using bitwise operators

后端 未结 3 1215
半阙折子戏
半阙折子戏 2021-01-25 19:35

How to change the sign of int using bitwise operators? Obviously we can use x*=-1 or x/=-1. Is there any fastest way of doing this?

I did a sm

3条回答
  •  一生所求
    2021-01-25 20:04

    Solution using high level language

    Questions like these are popular in interviews and competitive programming world .

    I landed here researching more solution for negation of a number without using - or + operator .

    For this :

    1. complement a number using ~ operator
    2. Then add 1 to the number obtained in step 1 using Half adder logic :

      int addNumbers(int x, int y) { 
                  if(y==0) return x; // carry is 0 return 
                  addNumbers(x^y,(x&y)<<1); }
      

    Here x^y performs addition of bits and x&y handles carry operation

提交回复
热议问题