Occurrences of a pattern in binary representation of a number | Function to return the count of occurrence of pat in binary representation of n ; To store decimal value of the pattern ; To store a number that has all ones in its binary representation and length of ones equal to length of the pattern ; Find values of $pattern_int and $all_ones ; If the pattern occurs in the last digits of $n ; Right shift $n by 1 bit ; Driver code
< ? php function countPattern ( $ n , $ pat ) { $ pattern_int = 0 ; $ power_two = 1 ; $ all_ones = 0 ; for ( $ i = strlen ( $ pat ) - 1 ; $ i >= 0 ; $ i -- ) { $ current_bit = $ pat [ $ i ] - '0' ; $ pattern_int += ( $ power_two * $ current_bit ) ; $ all_ones = $ all_ones + $ power_two ; $ power_two = $ power_two * 2 ; } $ count = 0 ; while ( $ n && $ n >= $ pattern_int ) { if ( ( $ n & $ all_ones ) == $ pattern_int ) { $ count ++ ; } $ n = $ n >> 1 ; } return $ count ; } $ n = 500 ; $ pat = "10" ; echo countPattern ( $ n , $ pat ) ; ? >