前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 371.Sum of Two Integers

LeetCode 371.Sum of Two Integers

原创
作者头像
大学里的混子
修改2018-10-29 17:10:50
3830
修改2018-10-29 17:10:50
举报
文章被收录于专栏:LeetCode

371.Sum of Two Integers

代码语言:txt
复制
371. Sum of Two Integers
Pick One
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3
Example 2:

Input: a = -2, b = 3
Output: 1

解法:

思路:

使用“与”与“异或”运算,其中按位“与”只是得到了进位信息,“异或”运算则是没有进位信息的“伪加法”。因此,要同时充分利用这两种运算求解加法运算。

代码语言:txt
复制
    public int getSum(int a, int b) {
        int carry = 0;
        while(b!=0) {
//            记录产生进位的位
            carry = a&b;
//            伪加法,没有进位的加法
            a = a^b;
//            将carry左移,移到更高的一位
            b = carry << 1;
        }
        return a;
    }

实际上,每次循环末尾得到的进位的b,将会在下一环循环和a再做加法,只有当b为零的时候结束循环。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 371.Sum of Two Integers
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档