首页 > 编程语言 > 详细

Leetcode 371. Sum of Two Integers JAVA语言

时间:2017-01-09 00:51:27      阅读:338      评论:0      收藏:0      [点我收藏+]
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.

题意:计算a+b,但是不许使用+和-

public class Solution {
    public int getSum(int a, int b) {
        //第一种
        while(a!=0){
            int carry=(a&b)<<1;
            b=a^b;
            a=carry;
        }
        return b;
        
        ////递归计算
        // if(b==0)return a;
        // int carry=(a&b)<<1;
        // int sum=a^b;
        // return getSum(sum,carry);
    }
}

技术分享

其实针对第一种方法,看图中就明白了。一开始搞乱了。

异或求得是俩数的无进位加法,而进位只会发生在1+1的时候,所以可以用&运算符,但是要左移一位。

就是这样,学习了。第一次做位运算。

Leetcode 371. Sum of Two Integers JAVA语言

原文:http://fulin0532.blog.51cto.com/6233825/1890223

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!