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
function countPattern ( n , pat ) { let pattern_int = 0 ; let power_two = 1 ; let all_ones = 0 ; for ( let i = pat . length - 1 ; i >= 0 ; i -- ) { let current_bit = pat . charAt ( i ) - ' ' ; pattern_int += ( power_two * current_bit ) ; all_ones = all_ones + power_two ; power_two = power_two * 2 ; } let count = 0 ; while ( n != 0 && n >= pattern_int ) { if ( ( n & all_ones ) == pattern_int ) { count ++ ; } n = n >> 1 ; } return count ; } let n = 500 ; let pat = " " ; document . write ( countPattern ( n , pat ) ) ;