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.
n=9
true
n=6
false
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.
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));}}
Free Resources