• [Swift]LeetCode600. 不含连续1的非负整数 | Non-negative Integers without Consecutive Ones


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10451440.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Given a positive integer n, find the number of non-negativeintegers less than or equal to n, whose binary representations do NOT contain consecutive ones.

    Example 1:

    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 <= 10^9


    给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。

    示例 1:

    输入: 5
    输出: 5
    解释: 
    下面是带有相应二进制表示的非负整数<= 5:
    0 : 0
    1 : 1
    2 : 10
    3 : 11
    4 : 100
    5 : 101
    其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。

    说明: 1 <= n <= 10^9


    Runtime: 8 ms
    Memory Usage: 18.5 MB
     1 class Solution {
     2     func findIntegers(_ num: Int) -> Int {
     3         var res:Int = 0
     4         var k:Int = 31
     5         var pre:Int = 0
     6         var f:[Int] = [Int](repeating:0,count:32)
     7         f[0] = 1
     8         f[1] = 2
     9         for i in 2..<31
    10         {
    11             f[i] = f[i - 2] + f[i - 1]
    12         }
    13         while (k >= 0)
    14         {
    15             if num & (1 << k) != 0
    16             {
    17                 res += f[k]
    18                 if pre != 0
    19                 {
    20                     return res
    21                 }
    22                 pre = 1
    23             }
    24             else
    25             {
    26                 pre = 0
    27             }
    28             k -= 1
    29         }
    30         return res + 1
    31     }
    32 }
  • 相关阅读:
    pgspider 一些ppt 截图
    postgres cassandra_fdw 扩展试用
    使用 postgres s3 fdw + cube.js 分析 csv 数据
    cube.js 集成s3 的一种方法
    postgres s3 fdw 试用
    cube.js 集成 elasticsearch 的一种变通方法
    使用postgres_fdw 串接elasticsearch fdw
    postgres elasticsearch fdw 学习
    使用vcpkg 管理c&&c++ 包
    postgres pg_cron 扩展连接远程pg server
  • 原文地址:https://www.cnblogs.com/strengthen/p/10451440.html
Copyright © 2020-2023  润新知