Occurrences of a pattern in binary representation of a number | Java 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
import java . util . * ; class solution { static 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 . charAt ( i ) - '0' ; pattern_int += ( power_two * current_bit ) ; all_ones = all_ones + power_two ; power_two = power_two * 2 ; } int count = 0 ; while ( n != 0 && n >= pattern_int ) { if ( ( n & all_ones ) == pattern_int ) { count ++ ; } n = n >> 1 ; } return count ; } public static void main ( String args [ ] ) { int n = 500 ; String pat = "10" ; System . out . println ( countPattern ( n , pat ) ) ; } }