zoukankan      html  css  js  c++  java
  • Leetcode: Sum of Two Integers && Summary: Bit Manipulation

    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.

    转自https://discuss.leetcode.com/topic/49771/java-simple-easy-understand-solution-with-explanation/2,注意里面对于减法的讲解

     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)

     1 // Iterative
     2 public int getSum(int a, int b) { 5 
     6     while (b != 0) {
     7         int carry = a & b;
     8         a = a ^ b;
     9         b = carry << 1;
    10     }
    11     
    12     return a;
    13 }
    14 
    15 // Iterative
    16 public int getSubtract(int a, int b) {
    17     while (b != 0) {
    18         int borrow = (~a) & b;
    19         a = a ^ b;
    20         b = borrow << 1;
    21     }
    22     
    23     return a;
    24 }
    25 
    26 // Recursive
    27 public int getSum(int a, int b) {
    28     return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
    29 }
    30 
    31 // Recursive
    32 public int getSubtract(int a, int b) {
    33     return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1);
    34 }
    35 
    36 // Get negative number
    37 public int negate(int x) {
    38     return ~x + 1;
    39 }
  • 相关阅读:
    第26月第13天 hibernate导包
    第26月第9天 getActionBar为空的解决办法
    第26月第8天 android studio 国内
    第26月第7天 mac如何matplotlib中文乱码问题
    第26月第6天 selenium
    第26月第3天 java gradle
    第26月第2天 vim javacomplete
    第25月第26天 dispatch_group_t dispatch_semaphore_t
    第25月25日 urlsession
    第25月第22日 django channels
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6103856.html
Copyright © 2011-2022 走看看