This article mainly introduces the PHP implementation of the statistical binary 1 of the number of algorithms, combined with examples of PHP string traversal, judgment, statistics and other related operational skills, the need for friends can refer to the next
In this paper, we describe the algorithm of 1 in the statistical binary system of PHP implementation. Share to everyone for your reference, as follows:
Problem
Enter a decimal integer that outputs the number of 1 in the binary representation. Where negative numbers are expressed in complement.
Solution Ideas
This is the problem of the single digit operation.
Solution one: By bitwise AND operation, by each bit and 1 and operation to find out the number of 1.
Solution two (optimal solution): A clever method, a binary number not 0, certainly at least one is 1, when this number minus one, its last 1 will become 0, the back of all 0 will become 1. For example, 10100, minus one will become 10011, and then with the original number 10100 and 10011 after the operation, you will get 10000, that is, through this operation, you can change a 1 to 0, so how many times a binary number can do such operations, there are how many 1.
Implementation code
Solution One function NumberOf1 ($n) {$count = 0; $flag = 1; while ($flag! = 0) { if ($n & $flag)! = 0) { $count + +; } $flag = $flag << 1; } return $count;}
Solution two function NumberOf1 ($n) {$count = 0; if ($n < 0) {//handle negative $n = $n &0x7FFFFFFF; + + $count; } while ($n! = 0) { $count + +; $n = $n & ($n-1); } return $count;}
Test the $num=45;echo $num. The binary is ". Decbin ($num)." <br/> "; Echo $num." Total ". NUMBEROF1 ($num). " a 1 ";
Operation Result:
Articles you may be interested in:
PHP Development with remote control server for the relevant explanation
A detailed description of how the CI framework (CodeIgniter) operates with Redis
PHP uses the Imagecopymerge () function to create a translucent watermark