338. Counting Bits
https://leetcode.com/problems/counting-bits/
Python
- Time: O(nlogn)
- Space: O(n)
from functools import reduce
class Solution:
def countBits(self, n: int) -> List[int]:
return [
reduce(lambda cur, i: cur+1 if i == '1' else cur, bin(i)[2:], 0)
for i in range(n+1)
]
Javascript
var countBits = function(n) {
const tmp = new Array(n + 1);
return [...tmp].map((b, i) => {
return i.toString(2).split('').reduce((acc, cur) => acc + Number(cur), 0);
})
};