leetcode: 600. Non-negative Integers without Consecutive Ones

Posted tmortred

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

以上是关于leetcode: 600. Non-negative Integers without Consecutive Ones的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 600 不含连续1的非负整数

Leetcode 600.不包含连续1的非负整数

LeetCode 600 不含连续1的非负整数[字典数 动态规划] HERODING的LeetCode之路

第十六周 Leetcode 600. Non-negative Integers without Consecutive Ones(HARD) 计数dp

LeetCode 68. 文本左右对齐 / 1894. 找到需要补充粉笔的学生编号 / 600. 不含连续1的非负整数(数位dp,好好学)

LeetCode动态规划(下篇)