zoukankan      html  css  js  c++  java
  • Sum of Two Integers

    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.

    Credits:
    Special thanks to @fujiaozhu for adding this problem and creating all test cases.

    I have been confused about bit manipulation for a very long time. So I decide to do a summary about it here.

    "&" AND operation, for example, 2 (0010) & 7 (0111) => 2 (0010)

    "^" XOR operation, for example, 2 (0010) ^ 7 (0111) => 5 (0101)

    "~" NOT operation, for example, ~2(0010) => -3 (1101) what??? Don't get frustrated here. It's called two's complement.

    1111 is -1, in two's complement

    1110 is -2, which is ~2 + 1, ~0010 => 1101, 1101 + 1 = 1110 => 2

    1101 is -3, which is ~3 + 1

    so if you want to get a negative number, you can simply do ~x + 1

    Reference:

    https://en.wikipedia.org/wiki/Two%27s_complement

    https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

    For this, problem, for example, we have a = 1, b = 3,

    In bit representation, a = 0001, b = 0011,

    First, we can use "and"("&") operation between a and b to find a carry.

    carry = a & b, then carry = 0001

    Second, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a,

    Then, we shift carry one position left and assign it to b, b = 0010.

    Iterate until there is no carry (or b == 0)

    // Iterative
    public int getSum(int a, int b) {
        if (a == 0) return b;
        if (b == 0) return a;
    
        while (b != 0) {
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        
        return a;
    }
    
    // Iterative
    public int getSubtract(int a, int b) {
        while (b != 0) {
            int borrow = (~a) & b;
            a = a ^ b;
            b = borrow << 1;
        }
        
        return a;
    }
    
    // Recursive
    public int getSum(int a, int b) {
        return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
    }
    
    // Recursive
    public int getSubtract(int a, int b) {
        return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
    }
    
    // Get negative number
    public int negate(int x) {
        return ~x + 1;
    }

    很好的讲解:

    http://www.geeksforgeeks.org/subtract-two-numbers-without-using-arithmetic-operators/

    reference: https://discuss.leetcode.com/topic/49771/java-simple-easy-understand-solution-with-explanation

  • 相关阅读:
    [From 3.1~3.4]
    [From 2.7]简单应用程序部署(程序集打包)
    [From 2.4]C#编译器和程序集链接器(以及一些它们的命令开关)
    [From 2.3]托管PE文件的组成
    [From 1.1~1.2]CLR的执行模型
    项目开发日志:Build AssetBundle——SpriteAtlas(已解惑)
    JDK所有版本下载链接
    Maven
    SEO优化
    Mysql字符集
  • 原文地址:https://www.cnblogs.com/hygeia/p/5755262.html
Copyright © 2011-2022 走看看