lundi 21 juin 2021

If else statements using basic algebra

With this question and correct answer via codingbat, why is my answer wrong?

Q. Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.

diff21(19) → 2
diff21(10) → 11
diff21(21) → 0

Correct solution:

public int diff21(int n) {
    if (n <= 21) {
        return 21 - n;
    } else {
       return (n - 21) * 2;
    }
}

My solution:

public int diff21(int n) {
    if (n>21) {
        return (n-21);
    } else {
        return 2 * (12-n);
    }
}

Aucun commentaire:

Enregistrer un commentaire