码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode: 600. Non-negative Integers without Consecutive Ones

时间:2020-06-13 17:32:34      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:iso   处理   ons   binary   orm   input   nes   leetcode   desc   

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

标签:iso   处理   ons   binary   orm   input   nes   leetcode   desc   

原文地址:https://www.cnblogs.com/tmortred/p/13118097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!