[英]Why am I getting a Time limit Exceeding? How can I improve the code?
目标是找到大于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 = 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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.