Program to find the Nth natural number with exactly two bits set | Set 2 | Java program for the above approach ; Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call
import java . util . * ; class GFG { static void findNthNum ( int N ) { int a = 0 , b , left ; int right , mid ; int t , last_num = 0 ; left = 1 ; right = N ; while ( left <= right ) { mid = left + ( right - left ) / 2 ; t = ( mid * ( mid + 1 ) ) / 2 ; if ( t < N ) { left = mid + 1 ; } else if ( t == N ) { a = mid ; break ; } else { a = mid ; right = mid - 1 ; } } t = a - 1 ; b = N - ( t * ( t + 1 ) ) / 2 - 1 ; System . out . print ( ( 1 << a ) + ( 1 << b ) ) ; } public static void main ( String [ ] args ) { int N = 15 ; findNthNum ( N ) ; } }