【leetcode】479. Largest Palindrome Product(Python & C++)
2017-09-27 19:59
302 查看
479. Largest Palindrome Product
题目链接479.1 题目描述:
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].
479.2 解题思路:
思路一:分为两步,一步是建立一个回文整数,一个是判断这个回文整数可以由两个n位数相乘得到。建立回文整数:利用to_string函数,将整数n转换为string得到S1,然后翻转string得到S2,最后利用stol函数,将string(S1+S2)转换为long型。
判断该回文数是否可以由两个n位数相乘得到:从10的n次方-1开始遍历,到10的n-1次方结束,依次获取回文整数。然后从10的n次方-1开始判断,并且其平方要大于这个回文整数。然后判断是否整除,并且整除后的除数是否小于10的n次方-1。否则条件,就返回这个回文数对1337取余。
479.3 C++代码:
1、思路一代码(402ms):class Solution135 { public: long buildPalindrome(int n) { string s = to_string(n); reverse(s.begin(), s.end()); return stol(to_string(n) + s); } int largestPalindrome(int n) { if (n == 1) return 9; int max = pow(10, n) - 1; int min = pow(10, n - 1); for (int i = max; i >= min;i--) { long mix = buildPalindrome(i); for (long j = max; j*j >= mix;j--) { if (mix%j == 0 && mix / j <= max) return mix % 1337; } } return -1; } };
479.4 Python代码:
1、思路一代码(超时)class Solution(object):#time limited def largestPalindrome(self, n): """ :type n: int :rtype: int """ if n==1: return 9 max=10**n-1 min=10**(n-1) def buildPalindrome(x): s=str(x)[::-1] a=long(str(x)+s) return a i=max while i>=min: mix=buildPalindrome(i) j=max while j*j>=mix: if mix%j==0 and mix/j<=max: return mix%1337 j-=1 i-=1 return -1
相关文章推荐
- [置顶] 【leetcode】28. Implement strStr()(Python & C++)(KMP算法)
- 【leetcode】680. Valid Palindrome II(Python & C++)
- 【leetcode】160. Intersection of Two Linked Lists(Python & C++)
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- 【leetcode】112. Path Sum(Python & C++)
- 【leetcode】605. Can Place Flowers(Python & C++)
- 【leetcode】58. Length of Last Word(Python & C++)
- leetcode 解题 String to Integer (atoi)(C&python)
- 【leetcode】1. Two Sum(Python & C++)
- 【leetcode】69. Sqrt(x)(Python & C++)
- 【leetcode】204. Count Primes(Python & C++)
- 【leetcode】507. Perfect Number(Python & C++)
- 【leetcode】278. First Bad Version(Python & C++)
- 【leetcode】14. Longest Common Prefix(Python & C++)
- leetcode Valid Palindrome C++&python 题解
- 【LeetCode with Python】 Pascal's Triangle II
- 【leetcode】2. Add Two Numbers(Python & C++)
- 【leetcode】219. Contains Duplicate II(Python & C++)
- 【leetcode】475. Heaters(Python & C++)
- leetcode Valid Palindrome C++&python 题解