Find smallest value of K such that bitwise AND of numbers in range [ N , N | Java program for the above approach ; Function is to find the largest no which gives the sequence n & ( n - 1 ) & ( n - 2 ) & ... . . & ( n - k ) = 0. ; Since , we need the largest no , we start from n itself , till 0 ; Driver Code
import java . io . * ; class GFG { public static int findSmallestNumK ( int n ) { int cummAnd = n ; int i = n - 1 ; while ( cummAnd != 0 ) { cummAnd = cummAnd & i ; if ( cummAnd == 0 ) { return i ; } i -- ; } return - 1 ; } public static void main ( String [ ] args ) { int N = 17 ; int lastNum = findSmallestNumK ( N ) ; int K = lastNum == - 1 ? lastNum : N - lastNum ; System . out . println ( K ) ; } }