Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

posted on 2016-03-21 12:15  Tonix  阅读(133)  评论(0编辑  收藏  举报