为什么在一个代码中显示时限超过问题而在其他代码中通过测试用例?

问题描述

我正在解决一个回文问题,但无法理解为什么我的代码1超出了时间限制,并且在代码2通过所有测试用例时无法正常运行? 我在执行这两个代码时都使用了相同的概念,但是在第二种情况下只使用了过程。@H_502_1@

这是两个代码:@H_502_1@

代码1 @H_502_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,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;
    }
    
}```

解决方法

我认为您将自己的int设置为 rev = 0。 在计算rev=rev*10+rem;时,您得到了错误的答案。 此外,在条件为no>0;的嵌套while循环中,no不会更改值。