0

This program output is showing time limit exceeded.what should i do now?

import java.util.Scanner; public class Difference{ public static void main(String[] args) { int num; int diff; int even=0; int odd=0; int count=1; int sum=0; Scanner input=new Scanner(System.in); num=input.nextInt(); while(num!=0) { sum=num%10; if(count%2==0) { even=sum+even; } else { odd=odd+sum; } num/=10; count++; } diff=odd-even; System.out.print(diff); } }

17th Aug 2019, 3:04 AM
Surya Krishna
Surya Krishna - avatar
10 Answers
+ 1
You seem to have alot of variables thus ur programme is stuck in time complexity
17th Aug 2019, 12:46 PM
Reca Resu
Reca Resu - avatar
+ 2
Within your while loop, you seem to have forgotten to change the value of num, which keeps it at whatever value it was initially and never lets the conditional within the loop return false (which is causing the time limit exceeded error). What you could do is include some calculation at the end of your loop to allow the value of num to go down and eventually reach 0 (perhaps something like num-=1)
17th Aug 2019, 3:20 AM
Faisal
Faisal - avatar
+ 2
My best guess would be that you may be entering too big of a number and the SL playground is just incapable of running for too long, returning that error. It's good to sometimes check with other IDEs as the code playground can limit you sometimes as to what you can do
17th Aug 2019, 3:36 AM
Faisal
Faisal - avatar
+ 1
Oh sorry I missed that! Running the code seems to work well for me, without returning any errors đŸ€” Are you running it on the SL code playground?
17th Aug 2019, 3:30 AM
Faisal
Faisal - avatar
+ 1
Yes,thanks for help.
17th Aug 2019, 3:37 AM
Surya Krishna
Surya Krishna - avatar
+ 1
My pleasure
17th Aug 2019, 12:47 PM
Reca Resu
Reca Resu - avatar
0
But i kept the exit condition num/=10,which will become zero in last.so,the while loop will exit.But even then it shows time limit and memory limit exceeded.
17th Aug 2019, 3:27 AM
Surya Krishna
Surya Krishna - avatar
0
Yes,i am.
17th Aug 2019, 3:32 AM
Surya Krishna
Surya Krishna - avatar
0
But thanks for your suggestions it executed successfully in eclipse.
17th Aug 2019, 3:33 AM
Surya Krishna
Surya Krishna - avatar
0
Thanks for your opinion,it executed successfully.
17th Aug 2019, 12:47 PM
Surya Krishna
Surya Krishna - avatar