How do I print a true statement if only 1 of 3 inputs is a positive number?

336 Views Asked by At

This is what I am currently using.

fun main() {
   val num1 = readLine()!!.toInt()
   val num2 = readLine()!!.toInt()
   val num3 = readLine()!!.toInt()
   
   println(num1 >= 1 || num2 >= 1 || num3 >= 1)
}
2

There are 2 best solutions below

0
some freelancer On

Try this , it will mean if any of this number positive number then it will return true. You can't go from num1 > 1 . because one is already positive number , in your code you checking if num1 is bigger that 1 . But your questions is about positive number , then use num1 > 0 . Done!

fun main() {
       val num1 = readLine()!!.toInt()
       val num2 = readLine()!!.toInt()
       val num3 = readLine()!!.toInt()
       
       println(num1 > 0 || num2 > 0 || num3 > 0)
    }
0
Sweeper On

One way is to make a list, and count

// prints true if exactly one of the numbers is positive
println(listOf(num1, num2, num3).count { it > 0 } == 1)

If you don't want to create the list, the logic is equivalent to (num1 > 0) XOR (num2 > 0) XOR (num3 > 0), except the case when all three are positive. We can replace XORs with !=, and handle the edge case, like this:

println(((num1 > 0) != (num2 > 0) != (num3 > 0)) &&
        !(num1 > 0 && num2 > 0 && num3 > 0))