New Solution - "Sum of Two Integers"

This commit is contained in:
Hao Chen 2018-06-26 00:00:49 +08:00
parent 44d5a405f4
commit 6daf90dae3
2 changed files with 39 additions and 0 deletions

View File

@ -49,6 +49,7 @@ LeetCode
|380|[Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./algorithms/cpp/insertDeleteGetRandom/InsertDeleteGetrandomO1.cpp)|Hard|
|377|[Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | [C++](./algorithms/cpp/combinationSumIV/combinationSumIV.cpp)|Medium|
|376|[Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | [C++](./algorithms/cpp/wiggleSubsequence/wiggleSubsequence.cpp)|Medium|
|371|[Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/description/) | [C++](./algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers.cpp)|Easy|
|350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp)|Easy|
|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy|
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium|

View File

@ -0,0 +1,38 @@
// Source : https://leetcode.com/problems/sum-of-two-integers/description/
// Author : Hao Chen
// Date : 2018-06-25
/***************************************************************************************
*
* 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.
***************************************************************************************/
class Solution {
public:
int getSum(int x, int y) {
// Iterate till there is no carry
while (y != 0) {
// carry now contains common
//set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at
//least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding
// it to x gives the required sum
y = carry << 1;
}
return x;
}
};