Lintcode A+B问题
来源:互联网 发布:java中转义字符 编辑:程序博客网 时间:2024/05/16 04:56
问题描述
- 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。
注意事项
你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。
说明
a和b都是 32位 整数么?
是的
我可以使用位运算符么?
当然可以
样例
如果 a=1 并且 b=2,返回3
笔记
《加法》,可以拆分成《异或得到的“加法不进位”》与《相与左移1的进位》的《加法》,因此,每次递归中都进行异或、相与左移1,然后,将得到的结果再做同样的操作,直到进位为0,递归停止。
代码
- 递归
class Solution {public: /* * @param a: The first integer * @param b: The second integer * @return: The sum of a and b */ int aplusb(int a, int b) { // write your code here, try to do it without arithmetic operators. if (b == 0) return a; int nocarry = a ^ b; int carry = (a & b) << 1; return aplusb(nocarry, carry); }};
- 循环
class Solution {public: /* * @param a: The first integer * @param b: The second integer * @return: The sum of a and b */ int aplusb(int a, int b) { // write your code here, try to do it without arithmetic operators. while (b != 0) { int tmpa = a ^ b; int tmpb = (a & b) << 1; a = tmpa; b = tmpb; } return a; }};
0 0
- LintCode-A + B 问题
- Lintcode A+B问题
- LintCode-A + B 问题
- LintCode A+b问题
- LintCode-A + B 问题
- lintcode -- A+B问题
- Lintcode:A + B 问题
- LintCode之A+B问题
- Lintcode 1 A + B 问题
- LintCode | 1. A + B 问题
- 【LintCode】1、A + B问题
- LintCode 1.A + B 问题
- [Lintcode] #1 A + B 问题
- LintCode-(1)A + B 问题
- LintCode-剑指Offer-(1)A+B问题
- lintcode刷题 A + B 问题 位运算
- LintCode-第1题 A+B问题
- 【lintcode】1、A+B问题【位运算】
- G-Milk
- How To Create A Client Server Application In Minutes[如何在几分钟的时间里编写一个客户机/服务器控制台程序]
- 古文构词之法
- 【HD 2187】老人是真的饿了 (sort+结构体+贪心)
- PowerShell SVN 添加文件并以指定时间和用户提交文件
- Lintcode A+B问题
- 欢迎使用CSDN-markdown编辑器
- 文章标题杭电What Is Your Grade?
- strspn()函数和strcspn()函数
- Linux 服务器搭建VPN(配置PPTP)
- java treeMap 已经排好序即输出{1=, 2=, 4=, 5=, 6=, 8=}
- Invert Binary Tree
- C - 开门人和关门人(结构体+sort)
- 栈的实现(数组方式)