[leetcode]: 371. Sum of Two Integers

来源:互联网 发布:跟淘宝联盟类似的网站 编辑:程序博客网 时间:2024/06/14 20:40

1.题目描述
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.

2.分析
首先想到电路里面加法器的实现:
保留位remain=a^b 0^1=1,1^0=1,0^0=0,1^1=0
进位carry=a&b<<1

3.代码

class Solution {public:    int getSum(int a, int b) {        int remain = a;        int carry = b;        while (carry) {            int temp = carry^remain;//异或            carry = (carry&remain) << 1;//进位            remain = temp;        }        return remain;    }};
0 0
原创粉丝点击