The FizzBuzz problem is a classic test given in coding interviews. The task is simple: Print integers 1 to N, but print “Fizz” if an integer is divisible by 3, “Buzz” if an integer is divisible by 5, and “FizzBuzz” if an integer is divisible by both 3 and 5.
Doing a "3 and 5" test makes the code more readable -- with more duplication:
if (theNumber is divisible by 3) and (theNumber is divisible by 5) then print "FizzBuzz" else if (theNumber is divisible by 3) then print "Fizz" else if (theNumber is divisible by 5) then print "Buzz" else /* theNumber is not divisible by 3 or 5 */ print theNumber end if
Here is some way of doing fizzbuzz solutions
1. Print FizBuzz using when
//".......Using when......."
fun printFizzBuzzWhen() {
for (i in 1..30) {
val result: String =
when {
i % 15 == 0 -> "FizzBuzz"
i % 3 == 0 -> "Fizz"
i % 5 == 0 -> "Buzz"
else -> "$i"
}
print("$result ")
}
}
output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz
2. Print on List using map
//".......Using map and print on list......."
fun printFizzBuzzMapOf() {
println((1..30)
.map {
i -> mapOf(0 to i,
i % 3 to "Fizz",
i % 5 to "Buzz",
i % 15 to "FizzBuzz")[0] })
}
output:
[1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz]
3. Check number is FIZZ or BUZZ or FIZZBUZZ or not (return number)
/--------find fizz or buzz or fizzbuzz-----------------
fun findFizzBuzzWhen(num: Int): String {
return when {
(num % 3 == 0 && num % 5 == 0) -> "FizzBuzz"
(num % 3 == 0) -> "Fizz"
(num % 5 == 0) -> "Buzz"
else -> "$num"
}
}
println("${findFizzBuzzWhen(15)}");
output: FizzBuzz
Learn more about fizzbuzz sotluion: https://wiki.c2.com/?FizzBuzzTest