LeetcodeSum of Two Integers

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeSum of Two Integers相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/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.

思路:
唉,这题虽然是easy,但是真好烦的一题,之前在hihocoder(还是其他oj)上好像也做过这题? 每次都是模拟32位运算然后遇到负数就搞不定了。。。参考别人的做法。

算法:

     public int getSum(int a, int b) {
       int c = 0;
       while(b!=0){
           c= a^b; //add
           b = (a&b)<<1;//carry
           a =c;
       }
       return a;
    }

以上是关于LeetcodeSum of Two Integers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCodeSum of Left Leaves 左叶子之和

LeetCodeSum of Left Leaves 左叶子之和

2. Add Two Numbers 两个数字相加

445. Add Two Numbers II 两个数字相加2

[LeetCode] 349 Intersection of Two Arrays & 350 Intersection of Two Arrays II

leetcode231-power-of-two