Problem 371. Sum of Two Integers

来源:互联网 发布:网络流行用语古称 编辑:程序博客网 时间:2024/05/24 01:47

http://blog.csdn.net/shijing_0214/article/details/10996951
题目地址:https://leetcode.com/problems/sum-of-two-integers/#/description
简单理解:

题目需要我们实现两个整数的加法,但是不能使用"+""-"操作符

我的解法:
使用逻辑运算符来实现:

1. bit的加法使用^运算符,如1^1=0,1^0=1,0^0=0;2. 进位的运算,使用&操作符和<<逻辑左移操作.1+1=10的运算过程为:1&1=1,1<<1= 10;

代码如下:

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