![]() |
Counting the number of zeros and ones in the binary representation of a number is a common task in computer science and programming. In this article, we will explore how to achieve this in PHP using different approaches. Table of Content Count Zeros and Ones in Binary Representation of a Number using Built-in FunctionsThis PHP program uses built-in functions to efficiently count the number of zeros and ones in the binary representation of a given number. It first converts the number to binary using decbin( ), then uses substr_count( ) to count the occurrences of “0” and “1” in the binary string. The counts are returned as an associative array. Example: Implementation to count zeros and ones in binary representation of a number. PHP
Output
Binary representation of 10: 1010 Number of zeros: 2 Number of ones: 2 Explanation:
Count Zeros and Ones in Binary Representation of a Number using Bitwise OperationsThis PHP program uses bitwise operations to count the number of zeros and ones in the binary representation of a given number. It iterates through each bit of the number, checking if it’s a zero or a one using the bitwise AND operator (‘&’). If it’s a one, it increments the $ones counter; otherwise, it increments the $zeros counter. The program then shifts the number one bit to the right (`$number >> 1`) to move to the next bit. This process continues until the number becomes zero. The counts are returned as an associative array. Example: Implementation to count zeros and ones in binary representation of a number. PHP
Output
Binary representation of 99: 1100011 Number of zeros: 3 Number of ones: 4 Explanation:
Count Zeros and Ones in Binary Representation of a Number using Recursive ApproachThis PHP program counts the number of zeros and ones in the binary representation of a given number using a recursive approach. It recursively divides the number by 2, counting the remainder as either a zero or a one, until the number becomes zero. The counts are returned as an associative array. Example: Implementation to count zeros and ones in binary representation of a number. PHP
Output
Number of Ones in 99 are: 4 Number of Zeroes in 99 are: 3 Explanation
|
Reffered: https://www.geeksforgeeks.org
PHP |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |