A + B Problem

来源:互联网 发布:打车软件对比分析 编辑:程序博客网 时间:2024/06/03 16:58

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

 Notice

There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.

Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.

也是一道比较基础的题了。但是感觉还是没完全掌握,这把举一个例子彻底弄明白。

本质上这道题就是位操作。因为不能使用加法,很容易联想到用位操作,那么怎么做呢? 那就是,转化成二进制的形式,对进位与不进位分开进行处理。用异或^, 得到的是两个数字在各个位上不相同的结果,也就是说,这个位置它不会产生进位,一个数里这一位是0,另一个数字这一位是1. 然后用&操作,计算得到进位,因为两个数字在这一位上的值都是1,说明会往前一位进位。知道进位的结果为0的时候,表明已经算出最终结果了。


举例:101+011=1000  (a, b)

1. a = 101, b = 011; a^b = 110, a&b = 001; 

2. a = 110, b = 001<<1=010; a^b =100, a&b = 010;

3. a = 100, b = 010<<1=100;a^b = 0; a&b = 100;

4. a = 0,b = 1000; a^b = 1000;a&b = 0;

最后结果:1000


代码:

public int aplusb(int a, int b) {        while(b != 0){            int temp = a ^ b;            int temp2 = a & b;            a = temp;            b = temp2<<1;        }        return a;    }        //public int aplusb(int a, int b) {    //     // write your code here, try to do it without arithmetic operators.    //     if(b == 0) return a;    //     return aplusb(a^b, (a&b)<<1);            // }};

 本质上都是一样的,就是采用加法结果与进位分开的思路来做。



0 0
原创粉丝点击