371. Sum of Two Integers
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.
public class Solution{
public int getSum(int a, int b) {
int c = a ^ b; //找出不同部分
int d = a & b ; //找到两个数共同部分 101 & 111 =101
int sum = c + (d<<1); //左移一位相当于乘2
return sum;
}
}
总结:不用+ 和 - 计算和,联想到计算机底层运算,将数转换成二进制的位操作。
转载请注明原文地址: https://ju.6miu.com/read-676727.html