📜  鲍姆·斯威特序列

📅  最后修改于: 2021-04-28 18:12:31             🧑  作者: Mango

Baum Sweet序列是0和1的无限二进制序列。如果数字n在其二进制表示中不具有奇数个连续的零,则该序列的第n个项为1,否则,第n个项为0。

The first few terms of the sequence are:
b1 = 1 (binary of 1 is 1)
b2 = 0 (binary of 2 is 10)
b3 = 1 (binary of 3 is 11)
b4 = 1 (binary of 4 is 100)
b5 = 0 (binary of 5 is 101)
b6 = 0 (binary of 6 is 110)

给定自然数n 。任务是找到Baum Sweet序列的第n个项,即检查它是否包含任何连续的奇数长度为零的块。

Input: n = 8
Output: 0
Explanations:
Binary representation of 8 is 1000. It 
contains odd length block of consecutive 0s. 
Therefore B8 is 0.

Input: n = 5
Output: 1

Input: n = 7
Output: 0

这个想法是通过n的二进制表示来运行一个循环,并计算存在的所有连续零块的长度。如果存在至少一个奇数长度的零块,则给定输入n的第n个项为0,否则为1。

// CPP code to find the nth term of the
// Baum Sweet Sequence
#include 
using namespace std;
  
int nthBaumSweetSeq(int n)
{
    // bitset stores bitwise representation
    bitset<32> bs(n);
  
    // len stores the number of bits in the 
    // binary of n. builtin_clz() function gives 
    // number of zeroes present before the 
    // leading 1 in binary of n
    int len = 32 - __builtin_clz(n);
  
    int baum = 1; // nth term of baum sequence
    for (int i = 0; i < len;) {
        int j = i + 1;
  
        // enter into a zero block
        if (bs[i] == 0) {
            int cnt = 1;
  
            // loop to run through each zero block
            // in binary representation of n
            for (j = i + 1; j < len; j++) {
  
                // counts consecutive zeroes 
                if (bs[j] == 0)                   
                    cnt++;
                else
                    break;
            }
  
            // check if the number of consecutive
            // zeroes is odd
            if (cnt % 2 == 1)
                baum = 0;
        }
        i = j;
    }
  
    return baum;
}
  
// Driver Code
int main()
{
    int n = 8;
    cout << nthBaumSweetSeq(n);
    return 0;
}
输出:
0