142.Sum of Two Integers
来源:互联网 发布:社交软件 编辑:程序博客网 时间:2024/06/03 20:17
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
/** * 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。 * 采用位运算来满足这个不用加减乘除的条件。 * Step1:先让两个数字相加,但是不做进位相当于做位异或的操作,00 = 0,11=0,01=1,10=1; * Step2:计算产生的进位,让两个数字位与操作,然后向左移动一位;备注,位与操作只有两个数都是1的时候才是1,其他结果都是0 * Step3:前两步的结果相加,重复前两个步骤直到进位为0. */public int getSum(int num1,int num2) {int sum;int carry;//产生的进位sum = num1^num2;carry = (num1&num2)<<1;while(carry != 0){num1 = sum;num2 = carry;sum = num1^num2;carry = (num1&num2)<<1;}return sum; }
0 0
- 142.Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- sum of two integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- 自己动手调试Android源码
- 实习杂记(28):PropertyAnimation学习
- MyBatis的ResultMaps
- matlab图形格式控制+程序结构
- [线性规划与网络流24题] 网络流常见模型
- 142.Sum of Two Integers
- POJ 1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors
- JAVA---udp数据的发送与接收
- 软件工程期末复习总结
- linux之管道
- 关于Direct3D绘制的顶点顺序
- 使用Spring MVC统一异常处理
- OpenMesh入门教程中文版