Smallest number greater or equals to N such that it has no odd positioned bit set | Java implementation of the approach ; Function to count the total bits ; Iterate and find the number of set bits ; Right shift the number by 1 ; Function to find the nearest number ; Count the total number of bits ; To get the position ; If the last set bit is at odd position then answer will always be a number with the left bit set ; Set all the even bits which are possible ; If the number still is less than N ; Return the number by setting the next even set bit ; If we have reached this position it means tempsum > n hence turn off even bits to get the first possible number ; Turn off the bit ; If it gets lower than N then set it and return that number ; Driver code
import java . util . * ; class GFG { static int countBits ( int n ) { int count = 0 ; while ( n > 0 ) { count ++ ; n >>= 1 ; } return count ; } static int findNearestNumber ( int n ) { int cnt = countBits ( n ) ; cnt -= 1 ; if ( cnt % 2 == 1 ) { return 1 << ( cnt + 1 ) ; } else { int tempnum = 0 ; for ( int i = 0 ; i <= cnt ; i += 2 ) { tempnum += 1 << i ; } if ( tempnum < n ) { return ( 1 << ( cnt + 2 ) ) ; } else if ( tempnum == n ) { return n ; } for ( int i = 0 ; i <= cnt ; i += 2 ) { tempnum -= ( 1 << i ) ; if ( tempnum < n ) { return tempnum += ( 1 << i ) ; } } } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { int n = 19 ; System . out . println ( findNearestNumber ( n ) ) ; } }