Home > OS >  Fizz-Buzz solution is not working properly in kotlin
Fizz-Buzz solution is not working properly in kotlin

Time:01-31

In the Fizz-Buzz problem, we replace a number multiple of 3 with the word fizz and a number divisible by 5 with the word buzz. If a number is divisible by both three and five, we replace it with the word"FizzBuzz." in a counting incremental loop.

But my code is not working properly. Please take a look and let me know what I am doing wrong.

for (i in 1..100){
        if ( i%5 == 0 || i%3 == 0) {
            println("FizzBuzz")}
        else if(i%5 == 0) {
            println("Buzz")}
        else if(i%3 == 0){
            println("Fizz")}    
        else {
            println(i)
        }    

    }

CodePudding user response:

You are using || instead of &&.

Replace:

if (i%5 == 0 || i%3 == 0) {
   println("FizzBuzz")
}

With:

if (i%5 == 0 && i%3 == 0) {
   println("FizzBuzz")
}

Or with:

if (i == 0) {
   println("FizzBuzz")
}

The more elegant solution is:

fun fizzBuzz(currentNumber: Int) = when {
  currentNumber % 15 == 0 -> "FizzBuzz" 
  currentNumber % 3 == 0 -> "Fizz"
  currentNumber % 5 == 0 -> "Buzz" 
  else -> "$currentNumber" 
}

for (currentNumber in 1..100) {
  print(fizzBuzz(currentNumber))
}
  • Related