<LeetCode> 题1: A+B求和
2016-07-08 14:10
260 查看
题目描述:
给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。思路:
由于不能适用+等运算符,根据提示,应该用位运算来完成。异或运算(^)可以模拟一种不进位加法,比如:10^11=01,每一位的加法就相当于该位相加,但不进位。接下来的问题就是如何解决进位问题!由于异或运算仅仅是忽略了进位,那么每次有进位发生时,异或运算相当于忽略了高位的一个1。
按位与(&)运算可以帮助我们判断该位是否有进位,如10&11= 10,得到的1就是需要进位的位。由于加法进位是加在高位上的,所以很自然的想到了把与运算的结果往左移一位,再和异或结果相加,即为最后结果。
代码:
/* * param a: The first integer * param b: The second integer * return: The sum of a and b * Notice: You should not use + or any arithmetic operators. * Example: Given a=1 and b=2 return 3 */ #include<iostream> using namespace std; class Solution { public: int aplusb(int a, int b) { if(b == 0) return a; else return aplusb(a^b, (a&b) << 1 ); } }; int main() { Solution so; cout<<"2+3="<<so.aplusb(2, 3) <<endl; cout<<"100+50="<<so.aplusb(100, 50) <<endl; system("pause"); return 0; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解