LeetCode 371. Sum of Two Integers

原题链接在这里: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 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1

题解:

两个数79和16 相加,不考虑进位相加得85, 只考虑进位进位是10, 85+10 = 95正好是结果.

二进制表示时, 不考虑进位0+0=0, 1+0=1, 0+1=1, 1+1=0, 其实就是xor.

只考虑进位0+0=0, 1+0=0, 0+1=0, 1+1=1, 其实就是&.

进位是放到更前以为,所以需要左移动一位, <<1.

可递推调用.

Time Complexity: O(1).

Space: O(1).

AC Java:

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

也可Iteration.

Time Complexity: O(1).

Space: O(1).

AC Java:

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

类似Add Two Numbers.

posted @ 2016-11-10 16:00  Dylan_Java_NYC  阅读(180)  评论(0编辑  收藏  举报