Occurrences of a pattern in binary representation of a number | C ++ program to find the number of times pattern p occurred in binary representation on n . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPattern ( int n , string pat ) { int pattern_int = 0 ; int power_two = 1 ; int all_ones = 0 ; for ( int i = pat . length ( ) - 1 ; i >= 0 ; i -- ) { int current_bit = pat [ i ] - '0' ; pattern_int += ( power_two * current_bit ) ; all_ones = all_ones + power_two ; power_two = power_two * 2 ; } int count = 0 ; while ( n && n >= pattern_int ) { if ( ( n & all_ones ) == pattern_int ) { count ++ ; } n = n >> 1 ; } return count ; } int main ( ) { int n = 500 ; string pat = "10" ; cout << countPattern ( n , pat ) ; }