-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathreverse_bits.cpp
58 lines (46 loc) · 1.21 KB
/
reverse_bits.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
// C++ program to reverse the bits of a number
/*
Given an integer, reverse its bits in its binary equivalent and
print the new number obtained in its decimal form
*/
#include <bits/stdc++.h>
using namespace std;
/*
The code first stores the lsb of the given number in a variable and then left shifts
the given number and gives this number to the lsb of the answer variable and then right
shifts it
*/
int reverse_bits(int n)
{
int rev = 0, rem;
// Traverse while there exist bits for the given number
while (n)
{
// Shift the bit of the reversed(answer) number to the right
rev = rev << 1;
//Stores the temporary lsb of the given number
rem = n & 1;
//Set the lsb of the answer variable with the stored value
rev = rem | rev;
//Drops the already processed lsb of the given number
n = n >> 1;
}
return rev;
}
int main()
{
int n, ans;
cout << "\nEnter the number? ";
cin >> n;
//Call the function
ans = reverse_bits(n);
cout << "The bits-reversed number is: " << ans << endl;
return 0;
}
/*
Time Complexity: O(n)
Space Complexity: O(1)
SAMPLE INPUT AND OUTPUT
Enter the number? 39
The bits-reversed number is: 57
*/