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;
}
}
我寫了一些代碼,但我不知道我在這里做錯了什么。
uj5u.com熱心網友回復:
與除錯決議邏輯相比,處理輸入、去除不相關部分(前導和/或尾隨零)、找到有效的 0 組、定義它們的長度然后計算出現次數或找到最長序列可能更方便:
- 使用
String::splitString::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 個零的序列
在線演示
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
測驗結果是一樣的。
uj5u.com熱心網友回復:
怎么樣:
String trimmed = convertToBinary(number).replaceAll("0 $","");
return (trimmed.length() - trimmed.replaceAll("10","").length())/2;
序列有多長并不重要,只要它里面有一個零并且不在字串的末尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335595.html
