gpt4 book ai didi

java - 为什么 Codility 不执行我的代码,而 Eclipse 会执行?

转载 作者:行者123 更新时间:2023-12-02 00:29:14 25 4
gpt4 key购买 nike

正在处理BinaryGap技术评估准备中的问题。无论出于何种原因,我的代码在 Eclipse 中编译并运行得很好,但在通过 Codility 运行时则不然。据称,这两个“IDE”都在 Java8 环境中执行。错误如下:

 Example test:   1041
WRONG ANSWER (got 0 expected 5)

Example test: 15
OK
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Gapper {
public static void main(String args[]){
Solution sol = new Solution(1041);
sol.solution(sol.getId());
}
}

class Solution{
private int count = 0;
private int id;
private String binary;
private static final String Regex = "(1{1})([0]{1,})(1{1})";
private Pattern pattern;
private Matcher mat;
private TreeSet<Integer> tree;
public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
public int solution(int N){
tree = new TreeSet<Integer>();
this.binary = Integer.toBinaryString(id);
for(int i = 0; i < this.binary.length(); i++){
this.pattern= Pattern.compile(Regex);
this.mat = this.pattern.matcher(this.binary.substring(i));
while(this.mat.find()){
if(this.mat.group().length() != 0){
tree.add(Integer.parseInt(this.mat.group().toString()));
}
}
}

int counter = 0;
if(!tree.isEmpty()){
String biggest = tree.last().toString();
for(int i = 0; i < (biggest.length()); i++){
if(biggest.charAt(i) == '0')counter++;
}
this.count = counter;
System.out.println("Binary gap = "+count);
return this.count;
}else{
return this.count;
}
}
public Solution(int id){
this.setId(id);
}
public Solution(){}
}

最佳答案

这是适用于所有情况的正确解决方案。

public int solution(int N) {

int curr = 0;
int max = 0;
int state = 0;

while (N > 0) {
int bit = N & 1;
switch (state) {
case 0:
if (bit == 1 )
state = 1;
break;
case 1:
curr = 0;
if (bit == 0) {
curr++;
state = 2;
}
break;
case 2:
if (bit == 0) {
curr++;
}
else {
state = 1;
if (curr > max) {
max = curr;
}
}
break;
}
N >>= 1;
}
return max;
}

关于java - 为什么 Codility 不执行我的代码,而 Eclipse 会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com