★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-qskmldvf-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Find the largest palindrome made from the product of two n-digit numbers.git
Since the result could be very large, you should return the largest palindrome mod 1337.github
Example:微信
Input: 2ide
Output: 987spa
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987code
Note:htm
The range of n is [1,8].blog
你須要找到由兩個 n 位數的乘積組成的最大回文數。get
因爲結果會很大,你只需返回最大回文數 mod 1337獲得的結果。
示例:
輸入: 2
輸出: 987
解釋: 99 x 91 = 9009, 9009 % 1337 = 987
說明:
n 的取值範圍爲 [1,8]。
440ms
1 class Solution { 2 func largestPalindrome(_ n: Int) -> Int { 3 var upper:Int = Int(pow(10.0,Double(n))) - 1 4 var lower:Int = upper / 10 5 let num:Int = lower + 1 6 for i in (num...upper).reversed() 7 { 8 var str:String = String(i) 9 var p:Int = Int(str + String(str.reversed()))! 10 var j:Int = upper 11 while(j * j > p) 12 { 13 if p % j == 0 14 { 15 return p % 1337 16 } 17 j -= 1 18 } 19 } 20 return 9 21 } 22 }
8ms
1 class Solution { 2 func largestPalindrome(_ n: Int) -> Int { 3 return [9, 987, 123, 597, 677, 1218, 877, 475][n-1] 4 } 5 }
440ms
1 class Solution { 2 func largestPalindrome(_ n: Int) -> Int { 3 if n==1 {return 9} 4 var max = UInt64(pow(Double(10), Double(n))) - 1 5 var min = max/10 6 7 8 for v in stride(from: max, to: min, by: -1) { 9 var ul = String(String(v).reversed()) 10 var ur = String(v) + ul 11 var u = UInt64(ur) 12 var x = max 13 while x*x >= u! { 14 if u! % x == 0 {return Int(u! % 1337)} 15 x -= 1 16 } 17 } 18 19 return 9 20 } 21 }