Find closest integer with the same weight | C ++ implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int NumUnsignBits = 64 ; unsigned long findNum ( unsigned long x ) { for ( int i = 0 ; i < NumUnsignBits - 1 ; i ++ ) { if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) { x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; return x ; } } } int main ( ) { int n = 92 ; cout << findNum ( n ) ; return 0 ; }