HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Two integers x & y

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
integerstwostackoverflow

Problem

Given two int values, print whichever value is larger. However if the two values have the same remainder when divided by 5, then the print the smaller value. However, in all cases, if the two values are the same, print 0.

This is what I have so far:

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);

    int x = scan.nextInt();
    int y = scan.nextInt();

    if(x > y || (x%5 == y%5 && y > x))
    {
        System.out.println(x);
    }
    else if (y > x || (x%5 == y%5 && x > y ))
    {
        System.out.println(y);
    }
    else if(x == y)
    {
        System.out.println("0");
    }
}


My score was 79/100 when I sent it to an online judge

What seems to be the problem?

Solution

-
What condition is the most important?

It seems like if (a == b) is the most important, which is what you then should handle first and use else for the rest.

-
Duplicated logic

You have written (x%5 == y%5 && y > x) twice in your code.

-
Using Math.min or Math.max

Instead of using if (x > y) and `if (x

Note: I can't guarantee that this will give you 100 points. I can't even guarantee that this will give you more points than Caridorc's solution with ternaries. But in my opinion, this is the better solution.

Code Snippets

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int x = scan.nextInt();
    int y = scan.nextInt();

    if (x == y) {
        System.out.println(0);
    } else if (x % 5 == y % 5) {
        System.out.println(Math.min(x, y));
    } else {
        System.out.println(Math.max(x, y));
    }
}

Context

StackExchange Code Review Q#108188, answer score: 10

Revisions (0)

No revisions yet.