-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_371_SumWithoutArithmeticOperatorsNegative.cpp
67 lines (58 loc) · 1.81 KB
/
LC_371_SumWithoutArithmeticOperatorsNegative.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* https://leetcode.com/problems/sum-of-two-integers/
* Given two integers a and b, return the sum of the two integers without using the operators + and -.
*/
class Solution {
public:
int getSum(int a, int b) {
// return a+b;
/*
//Iterative APPROACH of ++ --
if(b>0){
while(b!=0){
a++;
b--;
}
}
else if(b<0){
while(b!=0){
a--;
b++;
}
}
return a;
*/
/*
//HALF ADDER APPROACH and Bit Manipulation
int sum, carry;
while(b!=0){
sum = a^b; // sum without carries
carry = a & b; //shows each location where carry is needed
a = sum;
b = ((unsigned int)carry)<<1; // shift the carry left one column for adding
}//while loop
return a;
*/
int sum=a;
unsigned int carry = b; // sirf unsigned int likhne se purana code chlne lga wow.
while(carry>0)
{
sum = a ^ b; // sum of bits of a and b where atleast one is not set
carry = (a & b); // common set bits of a and b
// cout<<"sum "<<sum;
// cout<<" c "<<carry<<endl;
carry <<= 1; // shift carry one bit to add with
a = sum;
b = carry;
}
return sum;
//Power and LOG APPROACH
if(a == 0)
return b;
if(b == 0)
return a;
const auto e_a = exp(a);
const auto e_b = exp(b);
const auto e_ab = e_a * e_b;
return static_cast<int>(log(e_ab));
}
};