The Code is as follows:
Copy codeThe Code is as follows:
Function g (n ){
Var n = n. toString (2 );
Var count = 0;
For (var I = 0; I <n. length; I ++)
{
If (n [I] = "1 ")
Count ++;
}
Return count;
}
I think this writing is very troublesome. I suddenly thought that I could use the js split method to calculate the number of 1. The split parameter is regular \ 0 * \, which separates 1 in the string. The Code is as follows:
Copy codeThe Code is as follows:
Function f (n ){
Return n. toString (2). split (/0 */). length;
}
In this way, the code is very concise.
It is a pity that the efficiency of the two methods is tested. It is found that the efficiency of the regular split method is relatively low, and the time is about 2.5 times that of the for loop method.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Two errors are found in the original code.
First, in IE, strings cannot use array subscript to access the value at the specified position. They can only use charAt (index.
Second, in Chrome and Opera, the split (\ 0 * \) method calculates the number of 1 values, which may increase by 1 in some cases.
For example, if the binary value of 12 is 1100, the array generated by split (\ 0 * \) is [1, 1,]. That is to say, when the binary value does not end with 1, an empty array item will be generated at the end (this problem is not found in IE and Firefox ).
After thinking, we found that we do not need to use regular expressions to calculate the number of 1. We only need to use 1 as a parameter of the split method and 1 as a separator, the length of the split array should be 1 plus 1.
Copy codeThe Code is as follows:
Function f (n ){
Return n. toString (2). split ("1"). length-1;
}
In this way, the regular expression method is not used, and it is compatible with mainstream browsers, and its efficiency is not lower than the for Traversal method.
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]