Sum of Two Integers
来源:互联网 发布:装修网络平台有哪些 编辑:程序博客网 时间:2024/06/05 10:53
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.
这道题同样也是看了参考才有了思路。过程就是模拟二进制加法。将要加的数字分别计算进位和不进位的两个部分,然后再将这两部分想加,直到没有进位为止就是最后的结果。
举例 3+5
3^5 得到异或的结果,也就是不进位的每一位上的结果:
011
101
------
110
然后3&5
011
101
------
001
说明在最后一位上有进位。
然后递归下去,
110 跟 进位左移一位进行同样的计算,(001<<1 也就是 010)
---------------------------------------
110
010
------
100
110^ 010 = 100
110
010
------
010
110 & 010 = 010
-----------------------------------------
100 跟 010<<1:
100
100
-----
000
100 ^ 100 = 000
100
100
------
100
100 & 100 = 100
-------------------------------
000
1000
-----
1000
000
1000
------
0000
-----------------------最后一步
1000
代码:
public int getSum(int a, int b) { //b理解成进位 if(b ==0) return a; int add = a ^ b; int carry = (a & b)<<1; return getSum(add, carry); }
- 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
- 【Leetcode】Sum of Two Integers
- Oracle数据库面试练习题
- 微服务理论与实践(三)-微服务架构的基本能力和优缺点
- C++中vptr指针的存在
- 二叉树的各种遍历方法
- JavaWeb初级学习 之 JQuery-简介、选择器
- Sum of Two Integers
- mysql desc asc基本命令总结
- 做一个有自我要求的读者
- LeetCode 46. Permutations 解题报告
- Android事件分发<二>
- 学习C语言的一点感受
- win32主程序入口设置
- 剑指offer-包含min函数的栈
- python实现多进程_multiprocessing