Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | function to convert decimal to binary ; Count same bits in last block ; If n is 0 or it has all 1 s , then it is not considered to have equal number of 0 s and 1 s in blocks . ; Count same bits in all remaining blocks . ; Driver Code
< ? php function isEqualBlock ( $ n ) { $ first_bit = $ n % 2 ; $ first_count = 1 ; $ n = ( int ) ( $ n / 2 ) ; while ( $ n % 2 == $ first_bit && $ n > 0 ) { $ n = ( int ) ( $ n / 2 ) ; $ first_count ++ ; } if ( $ n == 0 ) return false ; while ( $ n > 0 ) { $ first_bit = $ n % 2 ; $ curr_count = 1 ; $ n = ( int ) ( $ n / 2 ) ; while ( $ n % 2 == $ first_bit ) { $ n = ( int ) ( $ n / 2 ) ; $ curr_count ++ ; } if ( $ curr_count != $ first_count ) return false ; } return true ; } $ n = 51 ; if ( isEqualBlock ( $ n ) ) echo " Yes " ; else echo " No " ; ? >