Count of values of x <= n for which ( n XOR x ) = ( n | C ++ implementation of the approach ; Function to return the count of valid values of x ; Convert n into binary String ; To store the count of 1 s ; If current bit is 1 ; Calculating answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countX ( int n ) { string binary = bitset < 8 > ( n ) . to_string ( ) ; int count = 0 ; for ( int i = 0 ; i < binary . length ( ) ; i ++ ) { if ( binary . at ( i ) == '1' ) count ++ ; } int answer = ( int ) pow ( 2 , count ) ; return answer ; } int main ( ) { int n = 5 ; int answer = countX ( n ) ; cout << ( answer ) ; }