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

    The code is as follows.

    public class Solution {
        public int getSum(int a, int b) {
            return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
        }
    }

    The above code may be rewritten to make it more readable.

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

    c stands for the carry bit of adding two integers. The sum of two integers can be decomposed into a summation bit (a & b) and a carry bit (a ^ b). The << 1 is to set the carry bit to the correct bit. The above process is repeated until no carry (c, stored in b, becomes 0). Then the sum is stored in a.

  • 相关阅读:
    6月17日
    6月16日
    6月15日
    6月14日
    6月13日
    6月12日
    6月11日
    6月10日
    6月8日
    6月5日
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/5860375.html
Copyright © 2011-2022 走看看