[英]why Time Limit exceed problem is showing in one code while passing test cases in other?
I was solving the next palindrome problem but failed to understand why my code 1 is showing time limit exceeded and not running properly while code2 has passed all test cases?我正在解决下一个回文问题,但未能理解为什么我的代码 1 显示超出时间限制并且在代码 2 已通过所有测试用例时无法正常运行? I have used the same concept while doing both the codes but just used procedure in the second case.
我在执行这两个代码时使用了相同的概念,但在第二种情况下只使用了过程。
Here are the two codes :这是两个代码:
code 1代码 1
int no=sc.nextInt();
boolean check=true;
int rem,temp,rev=0;
while(check)
{
no++;
temp=no;
while(temp>0)
{
rem=temp%10;
temp=temp/10;
rev=rev*10+rem;
}
if(rev==no)
{
check=false;
System.out.println(no);
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}```
code 2
``` public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
//Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
boolean check=true;
int rem,temp,temp2=1,rev=0;
System.out.println(no);
while(temp2!=0)
{
//no=no+1;
if(pallin(no))
{
System.out.println(no);
temp2=0;
}
no++;
}
/*while(no<900)
{ no++;
//StringBuilder str_no=new StringBuilder(no);
System.out.println(str_no.reverse());
if(str_no.equals(str_no.reverse()) )
{
check=false;
break;
}
}
if(check==false)
{
System.out.println(no);
}*/
}
private static boolean pallin(int no)
{
int rem,temp=no,rev=0;
while(temp>0)
{
rem=temp%10;
temp=temp/10;
rev=rev*10+rem;
}
System.out.println(rev);
if(rev==no)
{
System.out.println(rev);
return true;
}
return false;
}
}```
I think what is wrong is that you set your int rev=0.我认为错误的是您设置了 int rev=0。 When calculating
rev=rev*10+rem;
计算
rev=rev*10+rem;
you're getting a wrong answer.你得到了错误的答案。 Moreover, in the nested while loop with condition
no>0;
此外,在条件
no>0;
的嵌套 while 循环中no>0;
no is not changing value.不改变价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.