英文:
why Time Limit exceed problem is showing in one code while passing test cases in other?
问题
code 1
Scanner sc = new Scanner(System.in);
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;
}
}
code 2
public static void main(String[] args) {
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) {
if (pallin(no)) {
System.out.println(no);
temp2 = 0;
}
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 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?
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
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;
}
}```
</details>
# 答案1
**得分**: 0
我认为有问题的是你设置了 `int **rev=0.**`
在计算 `rev=rev*10+rem;` 时,你得到了错误的答案。
此外,在带有条件 `no>0;` 的嵌套 while 循环中,no 的值没有改变。
<details>
<summary>英文:</summary>
I think what is wrong is that you set your int **rev=0.**
When calculating `rev=rev*10+rem;` you're getting a wrong answer.
Moreover, in the nested while loop with condition `no>0;` no is not changing value.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论