Java 为什么我的时限超过了?如何改进代码?
目标是找到大于n的最小数字,该数字的数字和可以完全除以11。在我运行它之后,它什么也不返回Java 为什么我的时限超过了?如何改进代码?,java,Java,目标是找到大于n的最小数字,该数字的数字和可以完全除以11。在我运行它之后,它什么也不返回 public class M1 { public static int nextCRC(int n) { int crc; for (crc=n+1;crc!=0;crc++) { int sum=0; for (crc =n+1 ; crc!=0; crc = crc / 10) { int digit =
public class M1
{
public static int nextCRC(int n)
{
int crc;
for (crc=n+1;crc!=0;crc++)
{
int sum=0;
for (crc =n+1 ; crc!=0; crc = crc / 10)
{
int digit = crc % 10;
sum += digit;
if ( sum %11 == 0)
{
break;
}
}
}
return crc;
}
public static void main(String[] args)
{
M1 Model=new M1();
Model.nextCRC(20);
System.out.println(Model.nextCRC(20));
}
}
给你:
import java.math.*;
public class M1
{
public static int nextVal(int n)
{
int sum = 0;
int temp = n;
while(n>9){
sum = sum + n%10;
n = n/10;
}
sum = sum+n;
if((sum%11) == 0){
return temp;
}
return nextCRC(temp+1);
}
public static int nextCRC(int n) {
return nextVal(n+1);
}
public static void main(String[] args)
{
M1 Model=new M1();
Model.nextCRC(20);
System.out.println(Model.nextCRC(40));
}
}
以下是我的解决方案:
import java.util.stream.LongStream;
/*
the goal is to find the least number that is greater than n and the digit sum of that number can be fully divided by 11.
*/
public class M1 {
private static long nextCRC(int n) {
return LongStream.iterate(n + 1, l -> ++l)
.filter(l -> sumOfBase10Digits(l) % 11 == 0)
.findFirst().getAsLong();
}
private static long sumOfBase10Digits(final long num) {
if (num == 0) {
return 0;
} else {
return num % 10 + sumOfBase10Digits(num / 10);
}
}
public static void main(String... args) {
System.out.println(nextCRC(20));
System.out.println(nextCRC(200));
System.out.println(nextCRC(98765));
System.out.println(nextCRC(92));
}
}
好吧,它正在返回一些东西。它返回的是什么?与您期望它返回的是什么?好吧,您运行了两次
nextCRC(20)
,第一次就丢弃了输出。如果不这样做,您可以将运行时间减半。@azurefrog您没有听说过“计算一个CRC以丢弃”吗?我希望看到一个大于n(输入值)的数字,并且它的数字和可以完全除以11,我得到的是一个超过@carcigenicate的时间限制,简单地为他们编写提问者代码而没有解释可能是重复的,这是一个糟糕的答案。简单地为他们编写提问者代码而没有解释是一个糟糕的答案。其实我不是在寻找答案,只是想知道我的代码有什么问题。您的代码可以工作,但我的工作必须在一个int类中完成