zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    增删改查
    兴趣爱好
    兴趣爱好界面
    购物商城
    计算器
    安卓第四周作业
    安卓第一周作业
    第十五周作业
    十三周作业-集合
    第十三周上机练习
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6051275.html
Copyright © 2011-2022 走看看