rustlang
May 16, 2024

How to check whether number is even or not

RUST

In a nutshell: computer's numbers usually represented as binary sequence of 0 and 1. The first bit of that sequence is denoted as even or odd number where odd is 0 and even is 1. So you can check a number by using binary operation.

fn is_even(x: u32) -> bool {
  x & 1 != 0
}

fn is_odd(x: u32) -> bool {
  x & 1 == 1
}