fastest way to negate a number

后端 未结 7 1753
南旧
南旧 2020-12-29 03:20

I was thinking this morning here, what would be the fastest way to reverse a number of positive to negative and from negative to positive, of course, the simplest way might

7条回答
  •  醉话见心
    2020-12-29 03:49

    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

提交回复
热议问题