371. Sum of Two Integers
来源:互联网 发布:大学软件测试专业 编辑:程序博客网 时间:2024/06/09 20:18
Calculate the sum of twointegers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return3.
谷歌翻译:计算两个整数a和b的和,但不允许使用运算符+和 - 。
例:
给定a = 1和b = 2,返回3。
这题比较简单,可能是以前我以前做过类似的题目,所以说其实算法题大家多练习,多思考,还是可以提高的。贵在坚持。学习汇编的,应该能够很快了解它。代码如下:
非递归代码:
public class Solution {
public int getSum(int a, int b) {
int c=a^b;
int d=a&b;
while(d!=0){
d=d<<1;
a=c;
c=a^d;
d=a&d;
}
return c;
}
}
我做一本习题时,一种递归算法:
public class Solution {
public int getSum(int a, int b) {
if(b==0) return a;//没有进位的时候完成运算
int sum ,carry;
sum=a^b;//完成第一步没有进位的加法运算
carry=(a&b)<<1;//完成第二步进位并且左移运算
return getSum(sum,carry);//进行递归,相加
}
}
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 设计模式学习--简单工厂模式
- 摆动序列
- SQL 存储过程 where 条件 动态拼接
- 如何通过API调用alluxio 文件系统
- 无需Get更多技能,快速打造一个可持久化的任务调度
- 371. Sum of Two Integers
- 开源库 Natasha2016 ,让IL编程跑起来
- 旋涡JAVA笔记
- android UiAutomator写一个等待元素出现并点击的方法
- 如何在STM32F429上使用DSP库
- [LeetCode]301. Remove Invalid Parentheses
- WEB_Rember Me(自动登录) 的几种实现思路
- oracle11g OracleDBConsoleorcl服务无法启动问题
- [BZOJ2223][[Coci 2009]PATULJCI][主席树+特判]