不用加减乘除做加法
- 位运算
//链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
//来源:牛客网
//Java
public class Solution {
public int Add(int num1,int num2) {
while (num2!=0) {
int temp = num1^num2;
num2 = (num1&num2)<<1;
num1 = temp;
}
return num1;
}
}
//C++:
class Solution {
public
int Add(int num1, int num2)
{
return num2?Add(num1^num2,(num1&num2)<<1):num1;
}
};
- 汇编
//链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
//来源:牛客网
int add(int a, int b)
{
_asm
{
MOV EAX, a
MOV ECX, b
ADD EAX, ECX
}
}
- 自增自减
//链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
//来源:牛客网
public class Solution {
public int Add(int num1,int num2) {
if(num1>0){
while(num1--!=0)
num2++;
}
else if(num1<0){
while(num1++!=0)
num2--;
}
return num2;
}
}
- 通过指针
//链接:https://www.nowcoder.com/questionTerminal/59ac416b4b944300b617d4f7f111b215
//来源:牛客网
class Solution {
public:
int Add(int num1, int num2)
{
char* a = reinterpret_cast<char*>(num1);
return reinterpret_cast<long>(&(a[num2]));
}
};
- 通过函数
public int Add(int num1, int num2) {
return Integer.sum(num1, num2);
}
Integer.sum()源码
public static int sum(int a, int b) {
return a + b;
}