zoukankan      html  css  js  c++  java
  • 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.
    
  • 相关阅读:
    数据分析英国电商——数据分析可视化
    数据分析英国电商——数据预处理部分
    特征工程入门与实践—3 特征增强
    特征工程入门与实践—2 特征理解
    特征工程入门与实践 —1 特征工程简介
    正则表达式匹配
    linux学习笔记
    python深度学习基础
    Linux命令小记1
    AWS S3操作命令
  • 原文地址:https://www.cnblogs.com/tmortred/p/13118097.html
Copyright © 2011-2022 走看看