Find Next Sparse Number | C # program to find next sparse number ; Find binary representation of x and store it in bin . get ( ] . bin . get ( 0 ] contains least significant bit ( LSB ) , next bit is in bin . get ( 1 ] , and so on . ; There my be extra bit in result , so add one extra bit ; The position till which all bits are finalized ; Start from second bit ( next to LSB ) ; If current bit and its previous bit are 1 , but next bit is not 1. ; Make the next bit 1 ; Make all bits before current bit as 0 to make sure that we get the smallest next number ; Store position of the bit set so that this bit and bits before it are not changed next time . ; Find decimal equivalent of modified bin . get ( ] ; Driver program
using System ; using System . Collections ; class GFG { static int nextSparse ( int x ) { ArrayList bin = new ArrayList ( ) ; while ( x != 0 ) { bin . Add ( x & 1 ) ; x >>= 1 ; } bin . Add ( 0 ) ; int last_final = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( int ) bin [ i ] == 1 && ( int ) bin [ i - 1 ] == 1 && ( int ) bin [ i + 1 ] != 1 ) { bin [ i + 1 ] = 1 ; for ( int j = i ; j >= last_final ; j -- ) bin [ j ] = 0 ; last_final = i + 1 ; } } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += ( int ) bin [ i ] * ( 1 << i ) ; return ans ; } static void Main ( ) { int x = 38 ; Console . WriteLine ( " Next ▁ Sparse ▁ Number ▁ is ▁ " + nextSparse ( x ) ) ; } }