[Swift]LeetCode479. 最大回文数乘积 | Largest Palindrome Product
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9797766.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Find the largest palindrome made from the product of two n-digit numbers.
Since the result could be very large, you should return the largest palindrome mod 1337.
Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Note:
The range of n is [1,8].
你需要找到由两个 n 位数的乘积组成的最大回文数。
由于结果会很大,你只需返回最大回文数 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 }