Home > katas > Even or Odd (8kyu) [Dart]

Even or Odd (8kyu) [Dart]


This is a very popular kata. Let's solve it!

Chek kata on Codewars

Description:

Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.

Solution 1

Let's use Modulo operator (%) operator. It returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

4 % 2 // 0
3 % 2 // 1

If the number is even it returns 0 and if the number is odd it returns 1. Which converts to false or true accordingly.

String evenOrOdd(int number) {
  if (number % 2 == 0) {
    return 'Even';
  } else {
    return 'Odd';
  }
}

Let's use ternary operator to make it shorter.

String evenOrOdd(int number) {
  return (number % 2 == 0) ? "Even" : "Odd";
}

Or let's do oneliner here.

String evenOrOdd(int number) => (number % 2 == 0) ? "Even" : "Odd";

Solution 2

Using isEven/isOdd methods.

String evenOrOdd(int number) => number.isEven ? "Even" : "Odd";

Solution 3

Alternatively, we can create an array or map with 'Even' and 'Odd' values and return the first or second element.

Array version.

String evenOrOdd(int number) {
  return ['Even', "Odd"][number % 2];
}

Map verstion.

Map results = {true: 'Even', false: 'Odd'};

String evenOrOdd(int number) => results[number.isEven];
© 2021, Andrew Losseff