首页 > 后端开发 > C++ > 正文

在C程序中,将Baum Sweet序列进行翻译

王林
发布: 2023-08-26 22:17:02
转载
1171 人浏览过

在C程序中,将Baum Sweet序列进行翻译

在这里我们将看到 Baum Sweet 序列。该序列是一个二进制序列。如果数字n有奇数个连续的0,则第n位将为0,否则第n位将为1。

我们有一个自然数n。我们的任务是找到 Baum Sweet 序列的第 n 项。所以我们必须检查它是否有奇数长度的连续零块。

如果数字是 4,则该项将为 1,因为 4 是 100。所以它有两个(偶数)个0。

算法

BaumSweetSeqTerm (G, s) -

begin
   define bit sequence seq of size n
   baum := 1
   len := number of bits in binary of n
   for i in range 0 to len, do
      j := i + 1
      count := 1
      if seq[i] = 0, then
         for j in range i + 1 to len, do
            if seq[j] = 0, then
               increase count
            else
               break
            end if
         done
         if count is odd, then
            baum := 0
         end if
      end if
   done
   return baum
end
登录后复制

示例

#include <bits/stdc++.h>
using namespace std;
int BaumSweetSeqTerm(int n) {
   bitset<32> sequence(n); //store bit-wise representation
   int len = 32 - __builtin_clz(n);
   //builtin_clz() function gives number of zeroes present before the first 1
   int baum = 1; // nth term of baum sequence
   for (int i = 0; i < len;) {
      int j = i + 1;
      if (sequence[i] == 0) {
         int count = 1;
         for (j = i + 1; j < len; j++) {
            if (sequence[j] == 0) // counts consecutive zeroes
               count++;
            else
               break;
         }
         if (count % 2 == 1) //check odd or even
            baum = 0;
      }
      i = j;
   }
   return baum;
}
int main() {
   int n = 4;
   cout << BaumSweetSeqTerm(n);
}
登录后复制

输出

1
登录后复制

以上是在C程序中,将Baum Sweet序列进行翻译的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!