Thursday 3 May 2018

Algorithms | Reverse actual bits of the given number

Given a non-negative integer N, reverse the bits of N and print the number obtained after reversing the bits.

Note: actual binary representation of the number is being considered for reversing the bits, no leading 0’s are being considered.

Example
Input: 11
Output: 13

(11)10 = (1011)2.
Reversing the bits:
(1101)2 = (13)10.

Input: 12
Output: 3

(12)10 = (1100)2.
Reversing the bits:
(0011)2 = (3)10.


package com.microsoft.set166;
/**
 * Reverse actual bits of the given non-negative integer n.
 *
 * @author rajesh dixit
 * @since May 2, 2018 12:55:36 PM
 */
public class ReverseBits {

    /**
     * Method reverse the Bits to form a new number.
     *
     * @param value
     * @return reversed number
     */
    private static int getReverseBitNumber(int value) {
        int rev = 0;
        while (value > 0) {
            int lastBit = value & 1;

            rev = rev << 1;

            rev = rev | lastBit;

            value = value >> 1;
        }
        return rev;
    }
   
    /**
     * Driver method
     *
     * @param args
     */
    public static void main(String[] args) {

        int value = 14;
        int revValue = getReverseBitNumber(value);

        System.out.println(revValue);
    }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...