A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
What I've so far learned about Swift is that while the Playground is very cool for tinkering around, it definitely does not like big loops. So this time, I coded parts in the playground, but moved it over to an actual executable project to run the final code.
I'm interested in knowing any Swift tricks I missed. I did implement a new trick I learned in this solution, the stride
feature.
import Foundation
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
println("Time elapsed for \(title): \(timeElapsed) s")
}
extension Int {
func isPalindrome() -> Bool {
return self == self.reversed()
}
func reversed() -> Int {
var original: Int = self
var reversed: Int = 0
while original > 0 {
reversed *= 10
reversed += original % 10
original /= 10
}
return reversed
}
}
func largestPalindrome() {
var left: Int = 999
var right: Int = 999
var largestPalindrome: Int = 0
for left in stride(from: 999, through: 100, by: -1) {
for right in stride(from: left, through: 100, by: -1) {
let product: Int = left * right
if product > largestPalindrome && product.isPalindrome() {
largestPalindrome = product
}
}
}
println(String(largestPalindrome))
}
printTimeElapsedWhenRunningCode("Largest Palindrome", largestPalindrome)
The printTimeElapsedWhenRunningCode
function is borrowed from Brad Larson's answer here, and on my computer, it says the code is running in about 0.27 to 0.28 seconds.