【LeetCode】600. Non-negative Integers without Consecutive Ones

来源:互联网 发布:qq关系数据库 编辑:程序博客网 时间:2024/06/10 13:04

【LeetCode】600. Non-negative Integers without Consecutive Ones


【题目描述】

  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.

  Note: 1 <= n <= 109


【输入输出】

  Example 1:

Input: 5Output: 5Explanation: Here are the non-negative integers <= 5 with their corresponding binary representations:0 : 01 : 12 : 103 : 114 : 1005 : 101Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. 


【解题思路】

  1. int checkn(int n)当n自身满足条件是返回1,否则返回0

  2. table[i][0]存储二进制位数不大于i且以1开头以0结尾的数字个数,table[i][1]存储以1开头以1结尾的数字个数

  3. table2[i][0]存储二进制位数为i且以0结尾的数字个数,table2[i][1]存储以1结尾的数字个数

  4. 初始化ans = 1 + table[len-1][0] + table[len-1][1] + checkn(sn); // 0和二进制位数少1位的所有数字个数和自身(满足条件)

  5. 遍历num对应二进制串,若sn[i]=='1', ans += (table2[len-i-1][0] + table2[len-i-1][1]); // 将该为该为0时满足的个数

  6. 当遍历到第一组不满足条件1串时,break;


【代码】

class Solution {    int ans;    string toS(int n) {        if(n == 0) return "0";        string ans = "";        while(n != 0) {            ans = ((n % 2 == 0) ? "0" : "1") + ans;            n /= 2;        }        return ans;    }    int checkn(string s) {        for(int i = 1;i < s.length();i++) if(s[i] == '1' && s[i - 1] == '1') return 0;        return 1;    }public:    int findIntegers(int num) {        if(num <= 1) return num+1;        int table[33][2] = {{0, 0}, {0, 1}}, table2[33][2] = {{0, 1}, {1, 1}};        for(int i = 2;i < 33;i++) {            table[i][0] = table[i-1][0]+table[i-1][1], table[i][1] = table[i-1][0];            table2[i][0] = table2[i-1][0]+table2[i-1][1], table2[i][1] = table2[i-1][0];        }        for(int i = 2;i < 33;i++) {            table[i][0] += table[i-1][0], table[i][1] += table[i-1][1];        }        string sn = toS(num);        int len = sn.length();        ans = 1 + table[len-1][0] + table[len-1][1] + checkn(sn);        for(int i = 1;i < len;i++) {            if(sn[i] == '1') {                ans += (table2[len-i-1][0] + table2[len-i-1][1]);                if(sn[i-1] == '1') break;            }        }        return ans;    }};  // 6ms



阅读全文
0 0
原创粉丝点击