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

234 篇文章 1 订阅
177 篇文章 0 订阅

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一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值