码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode 371. Sum of Two Integers JAVA语言

时间:2017-01-09 00:53:24      阅读:215      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!