Wednesday, March 7, 2012

Reverse a number

1. Write a C code to reverse the bits in a number. Say a is an integer . Write a function which will reverse the the bits and give the output.

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t result = 0;
      
        // Process each bit position (up to 32 bits)
        // Early termination when n becomes 0 (optimization)
        for (int i = 0; i < 32 && n != 0; ++i) {
            // Extract the least significant bit (LSB) of n
            // Place it at position (31 - i) in the result
            result |= (n & 1) << (31 - i);
          
            // Shift n right by 1 to process the next bit
            n >>= 1;
        }
      
        return result;
    }
};



2.

int reverseDigits(int n) {
    int revNum = 0;
    while (n > 0) {
        revNum = revNum * 10 + n % 10;
        n = n / 10;
    }
    return revNum;
}

int main() {
    int n = 4562;
    printf("%d",reverseDigits(n));
    getchar();
    return 0;
}
2. Write the assembly level code to do the same.