Adding two numbers without using the addition operator

走远了吗. 提交于 2019-12-25 01:56:09

问题


In c ~ is 1's complement operator. This is equivalent to: ~a = -b + 1 So, a - ~b -1 = a-(-b + 1) + 1 = a + b – 1 + 1 = a + b

Can anyone explains this to me?


回答1:


From elementary school math we know

a = -(-a);

From twos complement we know that

-a = (~a) + 1  (invert and add one)

so we know that

a + b 
= a - (-b)      elementary math
= a - (~b + 1)  twos complement
= a - (~b) - 1   distribute the negative (elementary math)



回答2:


You are right that ~ is always 1's complement (aka bitwise not) in c. Where you are going wrong is this: C does not guarantee 2's complement for numbers. So all your calculations depend on using a major flavor of C.



来源:https://stackoverflow.com/questions/22735305/adding-two-numbers-without-using-the-addition-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!