func isOdd(n: Int) -> Bool {
if n % 2 == 1 {
return true
} else {
return false
}
}
So this function basically has me confused. let's say I called the function and input 9
isOdd(in:9)
I know that 9 is an odd number but how does the code work. If I do the math that the code implies which is n(9)/2 it equals 4.5. This result is checked as implied by the 2 equal symbols with 1. 4.5 is not equal to 1 so why does it return True.
CodePudding user response:
modulus division, gives the reminder when the first int is divided by the second int
and it returns an int
. So n % 2
returns 0
or 1
as a int
reminder.
That is why your function works. You can simplify your function to this:
func isOdd(n: Int) -> Bool { n % 2 != 0 }