LeetCode(371):两整数之和 Sum of Two Integers(Java)

2019.10.2 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

这道是《剑指Offer》原题:#数据结构与算法学习笔记#剑指Offer46:不用加减乘除做加法(Java、C/C++)

用位运算实现加减法。

异或(^)可以实现无进位相加的结果,与(&)可以表示进位的数位。实现进位加法时,只要将进位值右移一位与异或值相加即可,若再次产生进位,则再次相加。

例如2+3(0010 + 0011),异或值(0010 ^ 0011 = 0001),进位值(0010 & 0011 = 0010),进位值右移并与异或值相加(0100 ^ 0001 = 0101)结果为5。


传送门:两整数之和

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

不使用运算符 + 和 - ,计算两整数a 、b之和。

示例 1:
输入: a = 1, b = 2
输出: 3

示例 2:
输入: a = -2, b = 3
输出: 1


/**
 *
 * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
 * 不使用运算符 + 和 - ,计算两整数 a 、b 之和。
 *
 */

public class SumOfTwoIntegers {
    public int getSum(int a, int b) {
        int loc = a ^ b;
        int bit = (a & b) << 1;
        while(bit != 0){
            int carrybit = (loc & bit) << 1;
            loc = loc ^ bit;
            bit = carrybit;
        }
        return loc;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

你可能感兴趣的:(JAVA,数据结构与算法,LeetCode)