您的位置:首页 > 其它

LeetCode "Counting Bits"

2016-03-21 12:15 369 查看
Neat DP problem to go.

from math import *

class Solution(object):
def countBits(self, num):
ret = [0]
for i in range(1, num + 1):
if i & 1: # odd
ret += [ret[-1] + 1]
else:
prev = i - 1
trailing1s = (i | prev) - i
cnt = int(math.log(trailing1s + 1, 2))
ret += [ret[-1] + 1 - cnt]
return ret


If you don't like log(), you can use lookup table.

And, this is an amazing solution: https://leetcode.com/discuss/93501/simple-and-4-lines
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: