loading...

FizzBuzz in Rust

0xbf profile image Bo ・1 min read

FizzBuzz

For numbers from 1 to 30:

  • print "FizzBuzz" if number is divisible by 3 and 5
  • print "Fizz" if number is divisible by 3
  • print "Buzz" if number is divisible by 5

Solution 1: general loop

fn main() {
    let mut n = 0;
    while n <= 30 {
        if n % 3 == 0 && n % 5 == 0 {
            println!("FizzBuzz");
        } else if n % 3 == 0 {
            println!("Fizz");
        } else if n % 5 == 0 {
            println!("Buzz");
        } else {
            println!("{}", n);
        }
        n += 1;
    }
}

Solution 2: for_each + closure

fn main() {
    (1..=30).for_each(|x| {
        if x % 3 == 0 && x % 5 == 0 {
            println!("FizzBuzz");
        } else if x % 3 == 0 {
            println!("Fizz");
        } else if x % 5 == 0 {
            println!("Buzz");
        } else {
            println!("{}", x);
        }
    });
}

Discussion

pic
Editor guide