Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bitwise

Check if the first and last bit of a number are the only set bits

Ravi

Problem statement

Given a number n, check if the first and last bit of n is the only set bits. Only MSB (most-significant bit) and LSB (least-significant bit) are the set bits.

Example 1

  • Input: n=9
  • Output: true

Example 2

  • Input: n=6
  • Output: false

Solution

The corner case is n=1. In this case, the output is true, as MSB and LSB are the same set bit.

The idea here is that if we unset the LSB that is set, we are left with only the MSB set bit. In other words, subtracting one from the input number that has the MSB and LSB set unsets the LSB bit, resulting in a number that is a power of 2. Now, we only need to check if the resulting number is a power of 2 or not.

Note: Refer How to check if a number is a power of 2 in C++ to check if a number is a power of 2.

Code

class Main{

    static boolean powerOfTwo(int n) {
        return ((n & n - 1) == 0);
    }

    static boolean isOnlyFirstAndLastBitsAreSet(int n) {
        return (n == 1) || powerOfTwo(n - 1);
    }

    public static void main (String[] args) {
        int n = 9;
        System.out.println("Is first and last bits are the only set bits of " + n + "? " + isOnlyFirstAndLastBitsAreSet(n));
    }
}
First and last bit of number

RELATED TAGS

bitwise
RELATED COURSES

View all Courses

Keep Exploring