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.
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); // }};
本质上都是一样的,就是采用加法结果与进位分开的思路来做。
- problem 1000: A+B problem
- Problem 1000 A+B Problem
- Problem - 1000 A + B Problem
- A + B Problem
- A + B Problem
- 1000 A+B Problem
- 1001 A + B Problem
- A+B Problem
- 1000 A+B Problem
- A + B Problem
- A + B Problem
- 1000 A + B Problem
- 1000 A+B Problem
- A + B Problem
- A + B Problem II
- A + B Problem II
- POJ1001 -- A-B Problem
- A + B problem II
- Linux 下wifi 驱动开发(二)—— WiFi模块浅析
- 在HP-UX PA-RISC 平台下 RAC中CSSD failure但是节点不重启的问题
- 主瓣、栅瓣和旁瓣的定义
- PAT甲1123Is It a Complete AVL Tree (30) --AVL
- 交换俩个数组中的元素 用函数完成
- A + B Problem
- Linux 下wifi 驱动开发(三)—— SDIO接口WiFi驱动浅析
- web.py中如何返回Content-Length
- SVG和Canvas的区别
- vmware安装linux 成功后网络无连接的问题解决方案
- Android面试题及答案大全
- Linux 下wifi 驱动开发(四)—— USB接口WiFi驱动浅析
- 2011年嵌入式行业的八大趋势
- Swift 自定义转场动画 (没有封装)