lintcode-easy-A+B problem
2016-02-18 13:25
246 查看
Write a function that add two numbers A and B. You should not use
Example
Given
Note
There is no need to read data from standard input stream. Both parameters are given in function
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?
Clarification
Are a and b both
Yes.
Can I use bit operation?
Sure you can.
这道题相当于用编程语言写一个32位加法器,记不住可以搜一下
加法器原理:
sum = a^b^carry
carry = (a^b) | carry&(a^b)
逐个bit操作,把每一位的结果加到变量中去
这道题没有要求考虑溢出,不过面试可能有必要问一下,虽然我还没面过。
+or any arithmetic operators.
Example
Given
a=1and
b=2return
3
Note
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.
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?
Clarification
Are a and b both
32-bitintegers?
Yes.
Can I use bit operation?
Sure you can.
这道题相当于用编程语言写一个32位加法器,记不住可以搜一下
加法器原理:
sum = a^b^carry
carry = (a^b) | carry&(a^b)
逐个bit操作,把每一位的结果加到变量中去
这道题没有要求考虑溢出,不过面试可能有必要问一下,虽然我还没面过。
class Solution { /* * param a: The first integer * param b: The second integer * return: The sum of a and b */ public int aplusb(int a, int b) { // write your code here, try to do it without arithmetic operators. int carry = 0; int sum = 0; for(int i = 0; i < 32; i++){ sum = sum | (((a >> i) & 1) ^ ((b >> i) & 1) ^ carry) << i; carry = ((a >> i) & 1) & ((b >> i) & 1) | ((((a >> i) & 1) ^ ((b >> i) & 1)) & carry); } return sum; } };
相关文章推荐
- 常用函数集合
- 0218 图片的添加
- 今日放映影片api查询代码
- 常用宏
- Python学习之路-Day4
- Java线程(六):线程池
- 关闭防火墙
- 4. Tachyon安装-Tachyon本地模式搭建
- android程序自动更新安装详解
- Centos+Sersync+inotify实时同步数据文件(一)
- ubuntu lua安装
- rsync服务器简介与配置
- 第三章 类文件结构与javap的使用
- 数字签名
- Android实战技巧:ViewStub的应用
- BatteryManager--获取电量
- 用C/C++扩展你的PHP
- 简单的HTTP服务实现
- HUST 1358 Uiwurerirexb jeqvad(模拟解密)
- iOS学习笔记(十三)——获取手机信息(UIDevice、NSBundle、NSLocale)