码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 371 Sum of Two Integers

时间:2016-08-08 23:57:02      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

This problem is a little confusing to me at first. But after I read some articles online, I got to know that it requires bitwise operations.

So basically, we need to use "^" to calculate the sum of two integers, and "&" << 1 to calculate the carry.

Here is recursive way.

 1 public class Solution {
 2     public int GetSum(int a, int b) {
 3         if (b == 0) return a;
 4         
 5         int sum = a ^ b;
 6         int carry = (a & b) << 1;
 7         
 8         return GetSum(sum, carry);
 9     }
10 }

And here is iterative way.

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

注意这个while循环里面,需要我们先计算int carry = (a & b),不然会报错。

LeetCode 371 Sum of Two Integers

标签:

原文地址:http://www.cnblogs.com/wenchan/p/5751275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!