If we are engaged in front-end operations, we must have little chance to access binary data. What bitwise operations are, isn't it a problem that the underlying layer should consider? If we are engaged in front-end operations, we must have little chance to access binary data. What bitwise operations are, isn't it a problem that the underlying layer should consider?
I saw a question yesterday. It is related to binary, but it does not matter with bitwise operations. It can be easily solved with the help of JS's language features.
Description:
Write a function that receives a decimal positive integer as a parameter and represents it in binary format. Then, return the numbers equal to 1.
Here is an example:
1234Binary is10011010010.5Items1, So return5.
After reading this description, my first thought in my mind was how to convert it from decimal to binary (hate less ^_^ when the book was used ).
Fortunately, I have a good memory and soon thought of it.2Return the remainder and divide it2.2Return the remainder and divide it2... Until the result is0.
In the above process, use a variable to record the remainder1.
So we have the following practices:
var countBits = function(n) { var count = 0; while(n > 0){ var res = n % 2; if(res == 1){ count++; } n = parseInt(n / 2); } return count;};
This code and IDEA are both quite satisfactory, but they do not fully utilize the language features of JavaScript.
In JS, isn't there a ready-made API for converting decimal to binary?
Number. toString (2)In this case, will the binary string be obtained?
If all the results are returned, you can find the number 1 one by one and then return the result.
Well, the two methods above are both good, but the most efficient method is bitwise.
Finally, let's take a look at a bit operation solution written by a foreign Daniel!
function countBits(n) { for(c=0;n;n>>=1)c+=n&1 return c;}
Bright and blind eyes.
The above is JavaScript fun: Count the binary content. For more information, see the PHP Chinese website (www.php1.cn )!