Leetcode之路 371. Sum of Two Integers

来源:互联网 发布:酷炫爆炸js网站效果 编辑:程序博客网 时间:2024/06/02 06:09

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.
Tags:
Bit_Manipulation

2、Java代码实现

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

3、经验教训

  • 后悔当初没好好学数字逻辑和组成原理,对Bit的操作都不熟练……
  • Leetcode中一个比较好的discuss: Java simple easy understand solution with explanation,以下是其中代码:
// Iterativepublic int getSum(int a, int b) {    if (a == 0) return b;    if (b == 0) return a;    while (b != 0) {        int carry = a & b;        a = a ^ b;        b = carry << 1;    }    return a;}// Iterativepublic int getSubtract(int a, int b) {    while (b != 0) {        int borrow = (~a) & b;        a = a ^ b;        b = borrow << 1;    }    return a;}// Recursivepublic int getSum(int a, int b) {    return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);}// Recursivepublic int getSubtract(int a, int b) {    return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);}// Get negative numberpublic int negate(int x) {    return ~x + 1;}
0 0
原创粉丝点击