LeetCode-371. Sum of Two Integers
来源:互联网 发布:全球懂英语的人数 知乎 编辑:程序博客网 时间:2024/06/05 23:13
问题:https://leetcode.com/problems/sum-of-two-integers/?tab=Description
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.
分析:两个二进制数按位异或的结果就是两个二进制数进行相加但是没有进制的结果,比如:01+01 = 10,01^01=00,可以看到,若没有进制,则两者的结果是相同的。
按位与运算符的作用便是代替两数相加的进制位,两个二进制相加产生进制只有在两者均为1时才能产生进制,于是使用按位与运算符,由于按位与后的结果保存的是进制位,所以需要使用左移运算符(<<)向左移动一位。
代码里使用a保存按位异或的结果,b保存进制位,若b不等于0,则需要把进制位b与a继续相加(依然采用上述的算法代替加法运算),当b=0时(即没有产生进制),则所得的sum就是a与b相加的结果。
参考C++代码:
class Solution {public: int getSum(int a, int b) { int sum=0; while(b){ sum=a^b; b=(a&b)<<1; a=sum; } return sum; }};
0 0
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371.Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of Two Integers
- leetcode.371. Sum of Two Integers
- 371. Sum of Two Integers--LeetCode Record
- LeetCode—371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- iOS架构设计(解耦的尝试)之UI样式复用与布局管理
- JAVA HttpURLConnection Post方式提交传递参数
- 使用windows10+linphone-desktop最新版 编译linphone PC版
- 1011. World Cup Betting (20)
- Error: Cannot find module 'gulp-clone'问题的解决
- LeetCode-371. Sum of Two Integers
- 【Zookeeper】源码分析之请求处理链(二)
- mybatis(基于spring4)连接多个数据库
- Unreal4有哪些令你印象深刻拍案叫绝的设计
- 如何将jar包引入到web app libraries中
- 李白打酒 蓝桥杯
- 2016深圳杯D题 思路
- linux下载工具wget的参数使用
- CodeForces 706 C. Hard problem(dp)