Bit Counting
题目
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
分析
先把输入的正整数转换成二进制字符串,然后删掉字符串里的0,最后计算字符串长度。
需要用到的知识:
- parseInt() 函数,解析一个字符串,并返回一个整数
- num.toString(radix) radix为指定的进制数,默认为10,范围在2~36之间
- stringObject.replace(regexp/substr,replacement) 匹配正则式字符串并替换,
/0/g为全局匹配字符0
答案
1 | var countBits = function(n) { |

