Home > OS >  unable to find min and max outcome
unable to find min and max outcome

Time:07-08

input: p=1,r=55,x=5

output:5 50

after iterating from 1 to 55,if the sum of digits =5 then possible outcome will be 5,14,23,32,41,50 so the output is a smaller and greater outcome

I tried doing following code but I am getting index out of bond error. I think it is because if(sum==x) list.add(i); nothing is being added in this list.

import java.util.*;
public class wiley{
    static void find(int p,int r,int x){
        List<Integer> list= new ArrayList<Integer>();
        int sum=0,temp,rem;
        for(int i=p;i<r;i  ){
            temp=p;
            while(temp>0){
                rem=temp;
                sum =rem;
                temp=p/10;
            }
            if(sum==x) list.add(i);
            sum=0;
        }
        int l=list.get(0);
        int m=list.get(list.size()-1);
        System.out.println(l);
        System.out.println(m);
    }




public static void main(String args[]){
int p=1;
int r=55;
int x=5;
find(p,r,x);
}
}

CodePudding user response:

You are right, you get the error because nothing is added to the list. This is because in your for loop, you iterate over the variable i, yet you declare temp = p. Change this line to temp = i.

Also, you have to change temp=p/10 to temp=temp/10 and you're good to go.

In addition, you should rewrite your function so that it does not throw an exception even if there is no element in the list. For example, you could check if the list size is greater than 0 and only then try to access its elements.

  • Related