600. Non-negative Integers witho

2018-04-19  本文已影响7人  黑山老水

Description:

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.

Example:

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. 

Link:

https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/description/

解题方法:

DP1[i] = DP0[i - 1];
DP0[i] = DP1[i - 1] + DP0[i - 1];

Time Complexity:

O(lgn)

完整代码:

int findIntegers(int num) {
    if(!num)
        return 0;
    int cnt = 0;
    while(1 << cnt <= num) {
        ++cnt;
    }
    vector<int> DP0(cnt + 1, 0);
    vector<int> DP1(cnt + 1, 0);
    DP0[1] = 1;
    DP1[1] = 1;
    for(int i = 2; i <= cnt; i++) {
        DP0[i] = DP0[i - 1] + DP1[i - 1];
        DP1[i] = DP0[i - 1];
    }
    bool last = false;
    bool obRule = true;
    int result = 0;
    while(--cnt >= 0) {
        //curr postion is 1
        if(1 << cnt & num) {
            result += DP0[cnt + 1];
            if(last) {
                obRule = false;
                break;
            }
            last = true;
        }
        //curr position is 0
        else 
            last = false;
    }
    if(obRule)
        result += 1;
    return result;
}
上一篇下一篇

猜你喜欢

热点阅读