Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
预备知识:
整数在计算机中的表示方法(信息存储):
有符号数:既包括正数负数零;
计算机中表示有符号数最常见的方法就是补码形式:将字的最高有效位解释为负权。
while x,y>0,z<0, positive overflow;
while x,y<0,z>0, negative overflow,
class Solution {
public:
int getSum(int a, int b) {
int sum=a^b;
int c=a&b;
while(c)
{
a=c<<1;
b=sum;
sum=a^b;
c=a&b;
}
return sum;
}
};
并没有考虑溢出情况的存在,不清楚内置的+-是否存在溢出检测。
if(x>0&&y>0&&z<0) return erro("positive overflow");
if(x<0&&y<0&&z>0) return erri("negetive overflow");