371. Sum of Two Integers

来源:互联网 发布:淘宝卖话费怎么没利润 编辑:程序博客网 时间:2024/05/21 20:55

原题链接: 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.

思路: 这里用到了一个半加法的思想, 即两位单独的位相加其结果可以用异或得到, 进位可以用与得到. 然后对于两个数字来说同样可以延伸这个思想.

public class Solution {    public int getSum(int a, int b) {        while(a>0){            int x = a ^ b;            a = (a & b) << 1;            b = x;        }        return b;    }}

转载自:http://blog.csdn.net/qq508618087/article/details/51789576

0 0
原创粉丝点击