Reverse the bits of a number

Given a 32-bit integer, return the number with its bits reversed.

For example, given the binary number 1111 0000 1111 0000 1111 0000 1111 0000, return 0000 1111 0000 1111 0000 1111 0000 1111.

Example:

Input:  str = "11110000111100001111000011110000"
Output: 00001111000011110000111100001111

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string invertedBitsNumber(string str)
{
    for (int i = 0i < str.size(); i++)
    {
        if (str[i] == '1')
            str[i] = '0';
        else
            str[i] = '1';
    }
    return str;
}
int main()
{
    string str = "11110000111100001111000011110000";

    cout << invertedBitsNumber(str<< "\n";

    return 0;
}


No comments:

Post a Comment