题目:由6,6,7,7,8,8六个数字组成的6位数中,有多少是能被168整除的?
//: Playground - noun: a place where people can play
import UIKit
func isValid(num : Int) -> Bool {
var v = num
var i6 = 0
var i7 = 0
var i8 = 0
while(v > 0) {
let tmp = v % 10
if(tmp == 6) { i6+=1
} else if(tmp == 7) { i7+=1
} else if(tmp == 8) { i8+=1
} else {
return false
}
v = v/10
}
return (i6==2)&&(i7==2)&&(i8==2)
}
let start = Date(timeIntervalSinceNow: 0)
for i in 667788...887766 {
if (i % 168 == 0) && isValid(num : i) {
print(i)
}
}
//把 % 替换为加法能够快一点点
//let startValue = 667788 + (168 - 667788 % 168)
//for i in stride(from: startValue, through: 887766, by: 168) {
// if isValid(num: i) {
// print(i)
// }
//}
let end = Date(timeIntervalSinceNow: 0)
print(end.timeIntervalSince(start))
<blockquote>想想如果先执行isValid()
, 运行时间会相差多少。再验证一下。</blockquote>
网友评论