For example, I have the integer
a = 10;
and it's binary representation (for a 32 bit integer) is
00000000000000000000000000001010
and reversed, it becomes
01010000000000000000000000000000
Now I've seen this code, from this topcoder article that can accomplish this
x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
Now is there some straightforward way to achieve the same effect. Perhaps by converting our bitset into a string, and then reversing that? The constructors and method for converting bitset to a string of a bitset are so complicated I can't seem to figure out how to do this.
Here's what I tried so far
#include <bitset>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
#include <string>
using namespace std;
int main() {
const unsigned int k = 32;
int x = 10;
bitset<k> nf(x);
cout << nf << endl;
string str =
nf.to_string<char,string::traits_type,string::allocator_type>();
reverse(str.begin(), str.end() + str.size());
cout << str << endl;
return 0;
}
But I'm getting this as the output:
00000000000000000000000000001010
G;ÿJG¥±žGsÿkìöUàä˜\éä˜\é
Less code will win you some time in TopCoder SRMs. Following is what I would use in TopCoder SRMs (see it live here):
#include <algorithm>
#include <bitset>
#include <iostream>
#include <string>
int main() {
auto x = std::bitset<32>(10);
std::cout << x << std::endl;
auto str = x.to_string();
std::reverse(str.begin(), str.end());
auto y = std::bitset<32>(str);
std::cout << y << std::endl;
return 0;
}
This is the trivial inplace approach straight on a bitset:
template<std::size_t N>
void reverse(std::bitset<N> &b) {
for(std::size_t i = 0; i < N/2; ++i) {
bool t = b[i];
b[i] = b[N-i-1];
b[N-i-1] = t;
}
}
Without using any standard library functions (aside from printing the result):
#include<iostream>
#include<bitset>
const int size = sizeof(int)*CHAR_BIT;
int main()
{
int x = 10;
int r = 0;
for(int i = 0; i < size; i++)
{
r = r << 1 | (x & 1);
x >>= 1;
}
std::bitset<size> bits(r);
std::cout << "Reverse " << bits << std::endl;
}
Please check this one method :)
#include <iostream>
#include <bitset>
template<std::size_t N>
std::bitset<N> reverse(const std::bitset<N> &bit_set) {
std::bitset<N> reversed;
for (int i = 0, j = N - 1; i < N; i++, j--) {
reversed[j] = bit_set[i];
}
return reversed;
}
int main() {
std::bitset<32> b1(10);
std::bitset<32> reversed_b1 = reverse(b1);
std::cout << b1;
std::cout << "\nand reversed\n" << reversed_b1 << std::endl;
return 0;
}
User contributions licensed under CC BY-SA 3.0