Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fizz-Buzz solution is not working properly in kotlin

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)
        }    

    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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%15 == 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))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading