-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseBits.cpp
More file actions
38 lines (36 loc) · 882 Bytes
/
reverseBits.cpp
File metadata and controls
38 lines (36 loc) · 882 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
// bitset -> string, reverse -> bitset -> ulong
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
bitset<32> b(n);
string temp = b.to_string();
reverse(temp.begin(), temp.end());
return bitset<32>(temp).to_ulong();
}
};
// https://leetcode.com/problems/reverse-bits/discuss/1723115/2-0ms-CPP-Solution
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ans=0;
for(int i=0;i<32;i++){
if((n & (1 << i)))
ans |= 1 << ((31) - i);
}
return ans;
}
};
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t reverse=0; int flag{0};
if(n==0) return n;
while(n){
reverse<<=1;
reverse|=(n&1);
n>>=1;
flag++;
}
return reverse<<=(32-flag);
}
};