A + B Problem
2016-03-12 15:15
330 查看
Write a function that add two numbers A and B. You should not use
Notice
There is no need to read data from standard input stream. Both parameters are given in function
Clarification
Are a and b both
Yes.
Can I use bit operation?
Sure you can.
Example
Challenge
Tags
Notes
Given
+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-bitintegers?
Yes.
Can I use bit operation?
Sure you can.
Example
Challenge
Tags
Notes
Given
a=1and
b=2return
3
主要利用异或运算来完成 // 异或运算有一个别名叫做:不进位加法 // 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果 // 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方 // a & b就是a和b里都是1的那些位置,a & b << 1 就是进位 // 之后的结果。所以:a + b = (a ^ b) + (a & b << 1) // 令a' = a ^ b, b' = (a & b) << 1 // 可以知道,这个过程是在模拟加法的运算过程,进位不可能 // 一直持续,所以b最终会变为0。因此重复做上述操作就可以 // 求得a + b的值。
/** * Created by JZloveSnow on 16/3/12. */ class Solution24 { public int aplusb(int a, int b) { int result=0; while (b != 0) { int tempa = a^b; int tempb = (a&b)<<1; a = tempa; b = tempb; } return a; } }
相关文章推荐
- 罪与罚读后总结
- 进度条01
- MFC实现程序托盘
- iOS 时间,日期,字符串的处理
- 智能推荐系统
- Android四大组件之 Activity
- hihoCoder #1039 : 字符消除
- Android数据库升级总结
- js 九九乘法表
- 振兴中华(又见递归搜索)
- MongoDB 的优点
- BeagleBone Black开发记录一:SDK安装
- 分解质因数
- 搭建Pxe服务器无人听应答全自动安装SLES11 SP3系统
- 大数据平台基础架构和常用处理工具
- js对象定义,表格数据转成json上传提交
- 使用GridViewWithHeaderAndFooter为gridView添加页头的方法
- STM32串口中断接收和中断发送
- Kotlin Android入门学习一
- 七大排序算法总结 JavaScript <堆还没写…………待续>