Skip to content

Instantly share code, notes, and snippets.

@hiroakit
Last active June 28, 2017 01:31
Show Gist options
  • Save hiroakit/7dc4b54b7b77998f7f265fbc69b263d3 to your computer and use it in GitHub Desktop.
Save hiroakit/7dc4b54b7b77998f7f265fbc69b263d3 to your computer and use it in GitHub Desktop.
指定した年の範囲で閏年を算出 (Swift 3, Playground)
import UIKit
/// 閏年か判断する
///
/// - parameter year: 年
///
/// - returns: 閏年の場合にtrue、それ以外はfalse
func isLeapYear(year: Int) -> Bool {
// 4以上ではない場合は弾く
guard year >= 4 else {
return false
}
// 閏年の条件
// - 4で割り切れる年は閏年
// - 100で割り切れる年は閏年ではない
// - 400で割り切れる年は閏年
return year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)
}
/// 閏年の件数を返す
///
/// - parameter fromYear: 開始年
/// - parameter toYear: 終了年
///
/// - returns: 開始年と終了年の間に存在する閏年の件数
func countLeapYear(fromYear: Int, toYear: Int) -> Int {
var count = 0
for i in (fromYear ... toYear) {
if isLeapYear(year: i) {
count += 1
}
}
return count
}
print(countLeapYear(fromYear: 1, toYear: 2000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment