Hacker Rank Solutions in PHP - Day 03 - Intro to Conditional Statements

30 Days of Code - Day 3: Intro to Conditional Statements

Task
Given an integer, n, perform the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird

Complete the stub code provided in your editor to print whether or not n is weird.


Solution in PHP:

You can solve this task by implementing the conditional statements as described in the task description. Here's the PHP code to do that:

<?php

  $N = intval(trim(fgets(STDIN)));

  if ($N % 2 == 1) {

    // $N is odd

    echo "Weird";

  } else {

  // $N is even

  if ($N >= 2 && $N <= 5) {

    // $N is in the range [2, 5]

    echo "Not Weird";

  } elseif ($N >= 6 && $N <= 20) {

  // $N is in the range [6, 20]

  echo "Weird";

  } else {

  // $N is greater than 20

  echo "Not Weird";

  }

}


Here's how this code works:

  1. Read the input integer $N.
  2. Use if and elseif statements to check the conditions described in the task.
  3. If $N is odd, print "Weird."
  4. If $N is even and in the inclusive range of 2 to 5, print "Not Weird."
  5. If $N is even and in the inclusive range of 6 to 20, print "Weird."
  6. If none of the above conditions are met, print "Not Weird."

This code will determine whether the input integer is weird or not based on the conditions given in the task description.

Press ESC to close