[LeetCode]371. Sum of Two Integers
来源:互联网 发布:云计算发展与政策论坛 编辑:程序博客网 时间:2024/06/03 16:34
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.
题目:不用加号实现两个数字的和。
思路:首先两个数的和可以分解为 a^b加上(a&b)<<1。
a^b是不考虑进位的相加,后面是进位。
于是我很快写出了 return a^b+(a&b)<<1; 结果wrong
于是我修改 return a^b+((a&b)<<1); 继续wrong
最后 修改为 return (a^b)+((a&b)<<1); 成功AC。
为什么呢?查下运算符优先级就知道了。
感谢这个题目,不然我还以为^优先级是高与+号的。
当然这样是不行的,因为还是用了加号。
解决方法:当进位不为0的时候,我们可以继续进行位加法运算。
class Solution {public: int getSum(int a, int b) { while(b){ int c=(a^b); b=((a&b)<<1); a=c; } return a; }};
递归
class Solution {public: int getSum(int a, int b) { int c=(a^b); int d=((a&b)<<1); if(d!=0){ //这里不能写d>0,因为要考虑负数 return getSum(c,d); }else{ return c; } }};
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
- LeetCode解题报告 383. Ransom Note [easy]
- omnipeek安装教程
- Git代码管理工具
- PHP配置xdebug
- MFC消息映射机制以及画线功能实现
- [LeetCode]371. Sum of Two Integers
- javaWeb核心技术二
- Prometheus 系统监控方案
- 关系型数据库优化操作
- 华中农大HZAUOJ1104 Sum and XOR 异或瞎搞
- mac 下tomcat 安装与配置
- Database - 读书笔记--SQL必知必会07--创建计算字段
- Database - 读书笔记--SQL必知必会06--用通配符进行过滤
- 在CentOS 6.4中I安装OpenCobol 1.1