当前位置: 首页> 房产> 建材 > LeetCode-day33-600. 不含连续1的非负整数

LeetCode-day33-600. 不含连续1的非负整数

时间:2025/7/28 20:23:58来源:https://blog.csdn.net/weixin_43344005/article/details/140939257 浏览次数:0次

LeetCode-day33-600. 不含连续1的非负整数

  • 题目描述
  • 示例
    • 示例1:
    • 示例2:
    • 示例3:
  • 思路
  • 代码

题目描述

给定一个正整数 n ,请你统计在 [0, n] 范围的非负整数中,有多少个整数的二进制表示中不存在 连续的 1

示例

示例1:

输入: n = 5
输出: 5
解释:
下面列出范围在 [0, 5] 的非负整数与其对应的二进制表示:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
其中,只有整数 3 违反规则(有两个连续的 1 ),其他 5 个满足规则。

示例2:

输入: n = 1
输出: 2

示例3:

输入: n = 2
输出: 3

思路

数位DP(可套模板)

代码

class Solution:def findIntegers(self, n: int) -> int:@lru_cache(maxsize=None)def dfs(i: int,pre1: bool, is_limit: bool) -> int:if i < 0:return 1up = n >> i & 1 if is_limit else 1res = dfs(i-1,False,is_limit and up == 0)if not pre1 and up == 1:res += dfs(i-1,True,is_limit)return resreturn dfs(n.bit_length() -1 ,False,True)
关键字:LeetCode-day33-600. 不含连续1的非负整数

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: