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

Even or Odd (8kyu) [Swift]


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 Remainder 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.

func evenOrOdd(_ number:Int) -> String {
  if (number % 2 == 0) {
      return "Even"
  } else {
      return "Odd"
  }
}

Let's use ternary operator to make it shorter.

func evenOrOdd(_ number:Int) -> String {
    return (number % 2 == 0) ? "Even" : "Odd"
}

Solution 2

Using isMultiple(of:). Returns true if this value is a multiple of the given value, and false otherwise.

func evenOrOdd(_ number:Int) -> String {
    return number.isMultiple(of: 2) ? "Even" : "Odd"
}

Solution 3

Writing your own isEven function

func evenOrOdd(_ number:Int) -> String {
    return number.isEven()
}

extension Int {

    func isEven() -> String {
        return self.isMultiple(of: 2) ? "Even" : "Odd"
    }

}

Solution 4

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

func evenOrOdd(_ number:Int) -> String {
    return ["Even", "Odd"][number % 2]
}
© 2021, Andrew Losseff