What is wrong in this code?

import java.util.*;

class Codechef

{

public static void main(String[] args) {

    

    Scanner in = new Scanner(System.in);

    int tc,pr,n;

    boolean f1,f2;

    String s;

    try{

        tc=in.nextInt();

        while(tc-->0)

        {

            n=0;

            pr=in.nextInt();

            for(int i=101;;i++)

            {

                s=String.valueOf(i);

                f1=f2=false;

                for(int j=1;j<s.length();j++)

                {

                    if(s.charAt(j)-s.charAt(j-1)<0)

                        f1=true;

                    else if(s.charAt(j)-s.charAt(j-1)>0)

                        f2=true;

                    if(f1 && f2)

                    {

                        System.out.println(i);

                        n++;

                        break;

                    }

                }

                if((n*100)/i>=pr)

                {

                    System.out.println(i);

                    break;

                }

            }

            

        }

    }catch(Exception e)

    {

        return;

    }

}

}

What Problem are you trying to solve? :slight_smile:

1 Like
1 Like

Post link ro your submitted solution. Otherwise it’s hard to understand it.

1 Like

https://www.codechef.com/viewsolution/28390853

Your code doesn’t take into consideration the case when pr = 0 , for which the answer is 0. It prints 101 instead.
This worked

import java.util.*;

class Codechef
{
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int tc,pr,n;
		boolean f1,f2;
		String s;
		tc=in.nextInt();
		while(tc-->0)
		{
			n = 0;
			pr=in.nextInt();
			if(pr==0)
			{
				System.out.println(0);
				continue;
			}
			for(int i=101;;i++)
			{
				s = String.valueOf(i);
				f1 = f2 = false;
				for(int j=1;j<s.length();j++)
				{
					if(s.charAt(j)-s.charAt(j-1)<0)
						f1 = true;
					else if(s.charAt(j)-s.charAt(j-1)>0)
						f2 = true;
					if(f1 && f2)
					{
						n++;
						break;
					}
				}
				if((n*100)/i>=pr)
				{
					System.out.println(i);
					break;
				}
			}	
		}
	}
}

Also avoid using try and catch unnecessarily.
@utsavpatel It wouldn’t give NZEC error, just read my code once. It’s exactly your code without try and catch and with pr = 0 case taken.
You will never need try-catch in Competitive Programming.

2 Likes

https://www.codechef.com/viewsolution/28390853if i will not use try catch block then it is giving error NZEC