【leetcode】479. Largest Palindrome Product(Python & C++)
来源:互联网 发布:上市公司数据在哪里查 编辑:程序博客网 时间:2024/06/09 19:56
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
阅读全文
0 0
- 【leetcode】479. Largest Palindrome Product(Python & C++)
- leetcode 479. Largest Palindrome Product
- {LeetCode} 479. Largest Palindrome Product
- LeetCode: 479. Largest Palindrome Product
- leetcode 479. Largest Palindrome Product
- leetcode[Largest Palindrome Product]
- [Leetcode] 479. Largest Palindrome Product 解题报告
- 479. Largest Palindrome Product
- 479. Largest Palindrome Product
- 479. Largest Palindrome Product
- 479. Largest Palindrome Product
- leetcode 479. Largest Palindrome Product最大的回文乘积
- (Problem 4)Largest palindrome product
- Largest palindrome product
- Largest palindrome product
- Problem 4:Largest palindrome product
- Problem 4:Largest palindrome product
- PE 4 Largest palindrome product
- Reverse Linked List
- 原生js与jq对ajax的实现
- 消息队列RabbitMQ
- c#限制输入数字和小数点
- Recovery启动流程(3)--recovery.cpp分析
- 【leetcode】479. Largest Palindrome Product(Python & C++)
- 51Nod 1240:莫比乌斯函数
- Android进阶之路
- 1090: 最小生成树(模版 kruskal算法 )
- How I Mathematician Wonder What You Are! POJ
- C语言再学习-- 大端小端详解(转)
- 网络爬虫之东方财富网股票板块
- HTTP协议的基本概念和方法
- MySQL-按月分组查询