-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path371 Sum of Two Integers.cpp
More file actions
42 lines (37 loc) · 912 Bytes
/
371 Sum of Two Integers.cpp
File metadata and controls
42 lines (37 loc) · 912 Bytes
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
static int fastio=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
/*
Set nth bit of a number
number |= (1 << n);
*/
class Solution {
public:
int getSum(int a, int b) {
int ans=0;
int carry=0;
int curr;
int x,y;
for(int i=0;i<32;++i){
int f=(1<<i);
if(a&f) // i th bit of a
x=1;
else
x=0;
if(b&f) // i th bit of b
y=1;
else
y=0;
curr=x^y^carry; // current bit value
carry=x&y || ((x|y)&carry); // carry for next
// cout<<curr<<" "<<carry;
if(curr)
ans|=f; // set ith bit of a number
// cout<<endl;
}
return ans;
}
};