程序员面试金典——7.4加法运算替代
参考网址:https://www.nowcoder.com/profile/8858041/codeBookDetail?submissionId=15062497
一个知识点:
正整数按位取反等于其负数减一
负整数按位取反等于其正数减一
class AddSubstitution {
public:
int calc(int a, int b, int type) {
// write code here
int res = 0;
if(type == 1) {
int tmp = 0;
for(int i = 0; i < b; i++){
tmp += a;
}
res = tmp;
}
else if(type == 0 ) {
int tmp = a;
int count = 0;
while(tmp > 0&& tmp >= b) {
tmp = tmp + (~b) + 1;
count++;
}
res = count;
}
else {
res = a + (~b) + 1;
}
return res;
}
};