• 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.
    
  • 相关阅读:
    py计算程序运行时间-简易版
    py-冒泡排序
    py_冒泡排序
    Python测试函数运行时间
    py_二分查找
    Python发送get、post请求
    py_递归实例:汉诺塔问题
    递归实例:汉诺塔问题
    Jmeter断言实例—响应断言
    第十四天-linux命令及基础知识实战
  • 原文地址:https://www.cnblogs.com/tmortred/p/13118097.html
Copyright © 2020-2023  润新知