leetcode371题解
来源:互联网 发布:windows live安装包 编辑:程序博客网 时间:2024/05/29 15:18
leetcode 371.Sum of Two Integers
题目
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.
题目意思是:在不使用+和-运算的情况下,求两个整数的和。
解题思路
看到不能使用+和-,首先想到的应该就是位操作了。对于位操作来说,^和&是最常见的。我们先考虑一下这两个操作:
0^0=0,0^1=1,1^1=0(有进位) 可以看出异或做的是无进位的加法。
那怎么知道有没有进位呢?可以看到只有在两个bit都是1时,才有进位,而1&1=1(1&0=0)。
所以本题的思路如下:
1.按位做异或 a^b
2.计算是否有进位 (a&b)<<1 注意这里把结果左移一位,因为进位是加在高一位上的。
3.调用getSum再计算进位和无进位加法结果,即递归
AC代码如下
class Solution {public:int getSum(int a, int b) { if(b==0) return a; int sum=a^b; int carry=(a & b)<<1; return getSum(sum,carry); }};
总结
leetcode上easy难度,主要是熟悉位操作,算作积累吧。
在leetcode这道题的讨论区里面看到一篇特别好的位操作总结,分享一下。
https://discuss.leetcode.com/topic/50315/a-summary-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently
阅读全文
0 0
- leetcode371题解
- LeetCode371/104/389
- leetcode371: Sum of 2 Integers
- leetcode371. sum of two integers
- leetcode371-----Sum of Two Integers
- Leetcode371: Sum of Two Integers
- Leetcode371.Sum of Two Integers
- leetcode371:Sum of Two Integers
- leetcode371 位运算实现加法
- leetcode371. Sum of Two Integers
- leetcode371. Sum of Two Integers
- LeetCode371. Sum of Two Integers
- LeetCode371——Sum of Two Integers(不用+)
- 题解
- 题解
- 题解
- 题解
- 题解
- android点击button后的页面跳转
- 树状结构显示之递归练习并说明写递归代码的技巧
- 自定义标签配置详解
- 《算法分析与设计》Week 19
- [leetcode]124. Binary Tree Maximum Path Sum
- leetcode371题解
- 矩阵(matrix)应用大总结(二)HDU1588+HDU 5950+HDU 5015
- JSP简介——9大隐式对象
- RabbitMQ 三 角色权限
- Linux中制作压缩文件
- Linux学习总结(六)
- 计数排序
- Python基础 print()莫烦视频
- OpenStack E版虚机跨平台版本迁移