leetcode: 600. Non-negative Integers without Consecutive Ones

Description

Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.

Example

Input: 5
Output: 5
Explanation: 
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. 

Note

1 <= n <= 109

分析

和 902 一样,且边界条件处理要简单的多

code

class Solution(object):
    def findIntegers(self, num):
        """
        :type num: int
        :rtype: int
        """
        ll = [int(i) for i in '{0:b}'.format(num)]
        helper = [[0, 0] for i in range(len(ll))]
        helper[0][1] = 1
        helper[0][0] = 1


        if len(helper) > 1:
            helper[1][1] = 1
            helper[1][0] = 2

        for level in range(2, len(ll)):
            helper[level][0] = sum(helper[level-1])
            helper[level][1] = helper[level-1][0]

        ssum = 0

        for rlevel, v in enumerate(ll):
            level = len(ll) - 1 - rlevel
            if v == 0:
                if level == 0:
                    ssum += helper[0][0]
                continue
            if level > 0:
                if ll[rlevel:rlevel+2] == [1, 1]:
                    return ssum + sum(helper[level])
            if level == 0:
                if v == 0:
                    ssum += helper[0][1]
                else:
                    ssum += sum(helper[0])
            else:
                ssum += helper[level][0]

        return ssum

总结

You are here!
Your runtime beats 55.00 % of python submissions.
上一篇:xingtai -接小球游戏2.0


下一篇:DSX-600 CableAnalyzer™ 入门级铜缆认证仪