Find K 'th smallest number such that A + B = A | B | C ++ program for the above approach ; Function to find k 'th smallest number such that A + B = A | B ; res will store final answer ; Skip when j ' th ▁ position ▁ ▁ has ▁ 1 ▁ in ▁ binary ▁ representation ▁ ▁ as ▁ in ▁ res , ▁ j ' th position will be 0. ; j 'th bit is set ; If i ' th ▁ bit ▁ of ▁ k ▁ is ▁ 1 ▁ ▁ and ▁ i ' th bit of j is 0 then set i 'th bit in res. ; Proceed to next bit ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long kthSmallest ( long long a , long long k ) { long long res = 0 ; long long j = 0 ; for ( long long i = 0 ; i < 32 ; i ++ ) { while ( j < 32 && ( a & ( 1 << j ) ) ) { j ++ ; } if ( k & ( 1 << i ) ) { res |= ( 1LL << j ) ; } j ++ ; } return res ; } int main ( ) { long long a = 5 , k = 3 ; cout << kthSmallest ( a , k ) << " STRNEWLINE " ; return 0 ; }