mardi 29 septembre 2015

Comparing integers and creating the smallest integer possible from the digits of the given integers

I need to write the following method: accepts two integer parameters and returns an integer. If either integer is not a 4 digit number than the method should return the smaller integer. Otherwise, the method should return a four digit integer made up of the smallest digit in the thousands place, hundreds place, tens place and ones place.

For example biggestLoser(6712,1234) returns 1212 For example biggestLoser(19,8918) returns 19

Here's how I've started to write it:

public static int biggestLoser(int a, int b){
    if(a<9999 || b<9999){
        if(a<b)
            return a;
        else if(b<a)
            return b;
    }
    int at=a/1000;
    int ah=a%1000/100;
    int an=a%100/10;
    int ae=a%10;
    int bt=b/1000;
    int bh=b%1000/100;
    int bn=b%100/10;
    int be=a%10;
    if(at<bt && ah<bh && an<bn && ae<be)
        return at*1000+ah*100+an*10+ae;
    else if(at<bt && ah<bh && an<bn && be<ae)
        return at*1000+ah*100+an*10+be;
    else if(at<bt&& ah<bh && bn<an && ae<be)
    else return at*1000+ah*100+bn*10+ae;

However, it looks like I'm going to have to write way too many if statements, is there a shorter way to write the code?

Aucun commentaire:

Enregistrer un commentaire