【问题标题】:counting the sequences of 0s in binary number以二进制数计算 0 的序列
【发布时间】:2025-12-07 16:15:02
【问题描述】:
package com.company;

public
class ToBinary
    {
        public String convertToBinary( int n)
            {
                return Integer.toBinaryString( n );
            }
        public int howMany(int number)
        {
            String x = convertToBinary(number);
            char[] y = x.toCharArray();
            int counter=0; //how many seq in binary number
            /*
                sequence counts if 0s are surrounded by 1 f.ex 101 1001 is 1 sequence
                                                               100100101 is 3 seq
                                                               1010 is 1 seq
             */
            int temp=0;
            int maxGlobal=0;
            int maxLocal =0;
            for(int i=1;i<y.length-1;i++)
                {
                    if(y[i]!=y[i-1] && y[i]!=y[i+1])
                        counter++;
                    if(y[i]==0 && y[i-1]==0)
                        {
                            maxLocal +=1;
                        }
                    if(y[i]==0 && y[i+1]==1)
                    {
                        maxLocal +=1;
                        maxGlobal= maxLocal;
                        maxLocal =0;
                    }
                    else
                        continue;
                }
            System.out.println(maxGlobal);
            return counter;
        }

    }

我写了一些代码,但我不知道我在这里做错了什么。

【问题讨论】:

  • 您好,欢迎您。请说明您遇到的问题,例如指定输入、预期输出以及您得到的结果(错误的结果?异常?有什么问题吗?)
  • 与 couter 搭配时,输出的数字很好,但二进制数中最长的 0 序列却不是。我试图一步一步地在一张纸上做笔记,但我仍然不知道我被困在我递增计数器的位置下方。
  • 在 maxGlobal 中总是输出 0
  • 我认为您可能没有注意到的一件事是您正在检查 y[i] 的值,例如 0 和 1.. 当您应该检查“0”和“1”时,因为您将其转换为 char 数组。
  • 为什么 1011001 是 1 个序列,100100101 是三个序列 - 如果 0 的最小计数为 2,则应该是 2 个序列?

标签: java string binary sequence


【解决方案1】:

怎么样:

String trimmed = convertToBinary(number).replaceAll("0+$","");
return (trimmed.length() - trimmed.replaceAll("10","").length())/2;

序列有多长并不重要,只要它有一个零并且不在字符串的末尾。

【讨论】:

  • 确实如此,因为我有一个任务说要计算最长的序列有多长以及有多少。
  • String[] split = trimmed.split("1+") 也是如此,并在数组中找到长度最长的零字符串。
  • 我按照自己的方式做了,结果成功了。简单的解决方案是最好的,但感谢大家的帮助。
  • 我只使用了 char[x] y = x.toCharArray() 并在第二部分中使用了 for 循环、if 语句和 while
【解决方案2】:

与调试解析逻辑相比,处理输入、去除不相关部分(前导和或尾随零)、找到有效的 0 组、定义它们的长度然后计算出现次数或找到最长的序列可能更方便:

  • 使用String::split + String::replaceAll
private static IntStream toBinary(int n) {
    return Arrays.stream(Integer.toBinaryString(n)
            .replaceAll("(^0+1|10+$)", "1") // remove leading/trailing 0s
            .split("1+")
        ) // Stream<String>
        .mapToInt(String::length)
        .filter(i -> i > 1);
}

public static int howManyZeroSeqs(int n) {
    return (int) toBinary(n).count();
}

public static int maxZeroSeqLength(int n) {
    return toBinary(n).max().orElse(0);
}

测试

for (int i : new int[]{0b01001001000100, 0b010010010000100100010000}) {
    System.out.println("#seqs (" + Integer.toBinaryString(i) + ") = " + howManyZeroSeqs(i));
    System.out.println("max length (" + Integer.toBinaryString(i) + ") = " + maxZeroSeqLength(i));
}

输出:

#seqs (1001001000100) = 3
max length (1001001000100) = 3
#seqs (10010010000100100010000) = 5
max length (10010010000100100010000) = 4

  • 使用匹配模式来检测字符串末尾至少有 2 个零的序列

online demo

static Pattern ZEROSEQ = Pattern.compile("(?=1(0{2,}+)(?!$))1");
private static IntStream toBinary(int n) {
    return ZEROSEQ.matcher(Integer.toBinaryString(n))
        .results()
        .map(mr -> mr.group(1))
        .mapToInt(String::length);
}

(?=1(0{2,}+)(?!$))1 - ?=1(0{2,}+) 正向前瞻:1 后跟一个捕获组,用于至少 2 个零的序列

(?!$) - 负前瞻 - 不跟在字符串末尾的一组 0 1 - 关闭 1

测试结果是一样的。

【讨论】: