Question: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.
本题需要考虑正负数的情况。
补码等于~a+1,负数经过这样的运算就变为正数。补码和原码的转换是同一表达式。
异或:如果a、b两个值不相同,则异或结果为1。如果a、b两个值相同,异或结果为0。相当于没有进位的加法。
进位的实现:(a&b)<<1.有进位则向左移动一位,就是进位加。
Note:class域作用符对于静态成员函数可以使用类作用域运算符::。对于非静态成员函数必须要再定义A a;再a.function().
头文件要和主函数的CPP文件放在一起,VS里面不能全域查找。
VS注释快捷键:Ctrl+k,Ctrl+c;消除注释快捷键:Ctrl+k,Ctrl+u;
#pragma once
class Add {
public:
int getSum1(int a, int b);
int getSum(int a, int b) {
if (a < 0 && b < 0)//如果是负数就执行补码运算
{
a = (~a + 1);
b = (~b + 1);
int neg=getSum1(a, b);
neg = ~neg + 1;
return neg;//补码
}
else //不全是负数就执行该运算
{
return getSum1(a, b);
}
}
};
int Add::getSum1(int a, int b){
int xorab = a^b;
int carry = (a&b) << 1;
while (carry) {
xorab = a^b;
carry = (a&b) << 1;
a = xorab;
b = carry;
}
return xorab;
}
主函数:
#include<iostream>
#include"Add.h"
using namespace std;
int main() {
Add a;
int sum=a.getSum(1, -2);
cout << sum << endl;
}