Find closest integer with the same weight | Javascript 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
let NumUnsignBits = 64 ; function findNum ( x ) { for ( let i = 0 ; i < NumUnsignBits - 1 ; i ++ ) { if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) { x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; return x ; } } return Number . MIN_VALUE ; } let n = 92 ; document . write ( findNum ( n ) ) ;