I am looking for an answer to the Leap Year (last) exercise in Lesson 11 (Making Decisions.Playground) of App Development with Swift, can anyone help, please.
Leap Year Exercise in Lesson 11 (Making Decisions.Playground)
func isLeap (year: Int){
if (aYear % 4 == 0 && aYear % 100 == 0 && aYear % 400 == 0) || (aYear % 4 == 0 && aYear % 100 != 0){
print("YES")
} else {
print("NO")
}
}
isLeap(year: aYear) //function call
This seemed the most straightforward way to solve it.
A year is a leap year in two cases.
Case 1: The year equally divided by 4 AND equally divided by 100 AND while equally divided by 400.
OR
Case 2: The year is equally divided by 4 AND is NOT equally divided by 100.
func isLeapYear(_ year: Int) -> Bool {
if number(year, isDivisibleBy: 4)==false {
return false
}
else if number(year, isDivisibleBy: 100)==false {
return true
}
else if number(year, isDivisibleBy: 400){
return true
}
else {return false}}
Here is my solution; I don't know if it can be done in an easier way but this is how I did it and it works:
func isLeap(year: Int) {
if year % 4 == 0 && year % 100 != 0 && year % 400 == 0 {
print("YES")
} else if year % 4 == 0 && year % 400 == 0 {
print("YES")
} else if year % 4 == 0 && year % 100 != 0 {
print("YES")
} else if year % 100 == 0 {
print("NO")
} else {
print("NO")
}
}
isLeap(year: 2000) // write here whatever number you want
This also works fine:
I came up with the following logic, which works and is quite simple:
let aYear = 1300
func isLeap() {
if aYear % 400 == 0 {
print("YES")
} else if aYear % 4 == 0 && aYear % 100 != 0 {
print("YES")
} else {
print("NO")
}
}
isLeap()
Two simple ways to solve this exercise:
- Using build-in method "isDivisableBy":
if number(year, isDivisibleBy: 400 ) {
return true
}
else if number(year, isDivisibleBy: 100 ){
return false
}
else if number(year, isDivisibleBy: 4 ){
return true
} else {
return false
}
}
- Less elegant, defining three constants:
let isDivisableBy4 = 0
let isDivisableBy100 = 0
let isDivisableBy400 = 0
if year%400 == isDivisableBy400 {
return true
}
else if year%100 == isDivisableBy100 {
return false
}
else if year%4 == isDivisableBy4 {
return true
}
else {
return false
}
}
As you can see, the key is in proper order.