[LeetCode]371. Sum of Two Integers

来源:互联网 发布:算法的概念一等奖ppt 编辑:程序博客网 时间:2024/06/05 08:46

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.

class Solution {public:    int getSum(int a, int b) {        //将十机制加法转化为二进制加法        //非进位项用异或获得,进位项用与获得,进位项向左移位获得真正的进位数        //重复这个操作直到不能再进位        if(b == 0) return a;        int nocarrynum = a ^ b;        int carrynum = (a & b)<<1;        return getSum(nocarrynum, carrynum);    }};


0 0
原创粉丝点击