Home  >  Article  >  Web Front-end  >  JavaScript-specific method to count the number of 1's in binary split method_javascript skills

JavaScript-specific method to count the number of 1's in binary split method_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:28:021419browse

The code is as follows:

Copy code The code is as follows:

function g(n){
var n = n.toString(2);
var count = 0;
for(var i=0;i{
if(n[i] = = "1")
count ;
}
return count;
}

I thought it was very troublesome to write like this, but I suddenly thought if I could use the split method of js. Realize the calculation of the number of 1, and the parameter of split is regular
[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute ]

Discover the original There are two errors in the code.


First, under IE, strings cannot use array subscripts to access the value at a specified position, and can only use the charAt(index) method.

The second is under Chrome and Opera, split(


[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute ]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn