★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-bpmxboqz-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git
Example 1:github
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 的個數。less
示例 1:spa
輸入: 5 輸出: 5 解釋: 下面是帶有相應二進制表示的非負整數<= 5: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 其中,只有整數3違反規則(有兩個連續的1),其餘5個知足規則。
說明: 1 <= n <= 10^9code
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 }