资讯专栏INFORMATION COLUMN

[LeetCode] 371. Sum of Two Integers

mingzhong / 2237人阅读

Problem

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

Solution
class Solution {
    public int getSum(int a, int b) {
    //save 1-1 digits to carry
    //save different digit to a
    //left shift carry, save it to b, 
    //so carry is added to a, and got recalculated in the next while loop 
        while (b != 0) {
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        return a;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71934.html

相关文章

  • Leetcode PHP题解--D84 371. Sum of Two Integers

    摘要:题目链接题目分析相加给定的两个数,但不能使用或运算符。思路可以用二进制的与运算完成。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D84 371. Sum of Two Integers 题目链接 371. Sum of Two Integers 题目分析 相加给定的两个数,但不能使用+或-运算符。 思路 可以用二进制的与运算完成。此处用array_sum完成。 最终代码

    AJie 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • [LeetCode] 29. Divide Two Integers

    Problem Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator. Return the quotient after dividing dividend by divisor. The integer divisi...

    fai1017 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0

发表评论

0条评论

mingzhong

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<