Java If-Else | HackerRank Solution

Java If-Else | HackerRank solution

Java If-Else is one of the first problems in HackerRank's Java track. You read a number and print "Weird" or "Not Weird" based on four rules about odd, even and ranges. It is a decision-making exercise: the real test is whether you can take rules written in English and turn them into conditions that cover every number exactly once.

A beginner usually writes one if per rule and gets a correct answer. That is fine. But this problem also has a neat lesson hidden inside it. If you look at the rules as a table instead of as a list, four rules collapse into one condition. Learning to spot that kind of simplification is what turns "code that works" into "code that is easy to read and hard to break".

Problem

Read a positive integer n and classify it:

  • odd numbers are Weird;
  • even numbers from 2 to 5 (inclusive) are Not Weird;
  • even numbers from 6 to 20 (inclusive) are Weird;
  • even numbers above 20 are Not Weird.

Input format: a single line containing n.

Output format: the word Weird or the words Not Weird.

Constraints: 1 ≤ n ≤ 100.

Input 1:
3
Output 1:
Weird

Input 2:
24
Output 2:
Not Weird

Approach

Instead of coding the four rules one by one, first ask: when is the answer Weird? Going through the list, there are only two ways:

  1. the number is odd, or
  2. the number is even and sits between 6 and 20.

Every other number is Not Weird. So the whole problem becomes one if with an "or" (||) between those two conditions, and an else for everything else. You do not even need to check the 2..5 range or the "greater than 20" range separately, because they both lead to the same answer as the else.

To make the code read like the explanation, store each condition in a boolean variable with a clear name. Then the if line reads almost like English.

Dry run with n = 3: isOdd is true, so the if is true and we print Weird. With n = 24: isOdd is false. evenInMiddleRange is false because 24 is above 20. Both are false, so we go to else and print Not Weird. With n = 20: not odd, but even and inside 6..20, so Weird.

Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.close();

        boolean isOdd = n % 2 != 0;
        boolean evenInMiddleRange = !isOdd && n >= 6 && n <= 20;

        // Only two situations make n weird
        if (isOdd || evenInMiddleRange) {
            System.out.println("Weird");
        } else {
            System.out.println("Not Weird");
        }
    }
}

The Java you need to understand here:

  • Scanner and nextInt(): new Scanner(System.in) connects a reader to standard input, and nextInt() converts the next token into an int.
  • % (modulus) gives the remainder of a division. n % 2 is 0 for even numbers and non-zero for odd ones.
  • boolean is a type that holds only true or false. A comparison like n % 2 != 0 already produces a boolean, so you can store it directly.
  • !, &&, || are "not", "and", "or". Java also short-circuits: if the left side of || is true, the right side is never evaluated.

The earlier code on this page used the same idea in one line, n%2==1 || (n>=6 && n<=20). Note that the bracketed part does not check for even. It still works because odd numbers in 6..20 are already caught by the left side, so they give Weird either way. The named variables above just make that reasoning visible. The old version also used print without a newline and a lowercase class name; HackerRank accepts both here, but println and a class named Solution are the safer defaults.

I checked every value from 1 to 100 against the four original rules, plus the samples. The boundary values 2, 5, 6, 20 and 22 are where mistakes usually show up, and they all come out right.

Output

Weird

That is for input 3. For input 24 it prints Not Weird.

Complexity

O(1) time and O(1) space. A couple of comparisons, regardless of n.

Common mistakes

  • Mixing && and || without brackets and getting the wrong grouping. When in doubt, add brackets or use named booleans as above.
  • Off-by-one on the range, writing n < 20 instead of n <= 20. The word "inclusive" means the end points count.
  • Using = (assignment) instead of == (comparison) inside a condition. With an int, Java refuses to compile it, which is a helpful error to recognise.
  • Output spelling. Not Weird needs a capital W and exactly one space.

The same rules appear in Day 3: Intro to Conditional Statements, where we solve it with an if-else-if chain instead. Next in the Java track: Andrew and COVID.

Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.

More HackerRank solutions All coding problems MCQ practice

Comments

Answered 0/0Correct 0