• 371. 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.

    这道题让我们实现两数相加,但是不能用加号或者其他什么数学运算符号,那么我们只能回归计算机运算的本质,位操作Bit Manipulation,我们在做加法运算的时候,每位相加之后可能会有进位Carry产生,然后在下一位计算时需要加上进位一起运算,那么我们能不能将两部分拆开呢,我们来看一个例子759+674

    1. 如果我们不考虑进位,可以得到323

    2. 如果我们只考虑进位,可以得到1110

    3. 我们把上面两个数字假期323+1110=1433就是最终结果了

    然后我们进一步分析,如果得到上面的第一第二种情况,我们在二进制下来看,不考虑进位的加,0+0=0, 0+1=1, 1+0=1, 1+1=0,这就是异或的运算规则,如果只考虑进位的加0+0=0, 0+1=0, 1+0=0, 1+1=1,而这其实这就是与的运算,而第三步在将两者相加时,我们再递归调用这个算法,终止条件是当进位为0时,我们直接返回第一步的结果,参见代码如下:

    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;
    }
    

      

  • 相关阅读:
    hdu 2014 青年歌手大奖赛_评委会打分
    java 图像灰度化与二值化
    hdu 2010
    如何搞定IE+google双内核的360浏览器表单自动回填兼容问题
    多预览小图焦点轮播插件lrtk
    多功能前台交互效果插件superSlide
    自适应标题延展线写法
    二级菜单延迟隐藏
    各种浏览器的Hack写法(chrome firefox ie等)
    jQuery treetable【表格多重折叠树功能及拖放表格子元素重新排列】
  • 原文地址:https://www.cnblogs.com/apanda009/p/7287174.html
Copyright © 2020-2023  润新知