zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    jenkins+maven+svn的自动化部署
    python+selenium遇到鼠标悬停不成功可以使用js进行操作
    robot framework环境搭建
    selenium+python定位元素方法
    selenium+python元素操作
    selenium+python等待时间
    selenium+python浏览器窗口的切换
    jmeter学习(七)连接mysql 数据库
    jmeter学习(六)集合点和关联
    jmeter学习(五)参数化
  • 原文地址:https://www.cnblogs.com/strengthen/p/10451440.html
Copyright © 2011-2022 走看看