本文共 1648 字,大约阅读时间需要 5 分钟。
题目:
Find the largest palindrome made from the product of two
Since the result could be very large, you should return the largest palindrome modn
-digit numbers.1337
. Example:Input: 2Output: 987Explanation: 99 x 91 = 9009, 9009 % 1337 = 987Note:
The range of n is[1,8]
.
解释:
找到两个n
位数字的乘积所能构成的最大的回文数字。 解法1: 构建回文+校验除数,但是python速度比较慢。n=9的时候会超时。 python代码: class Solution: def largestPalindrome(self, n): """ :type n: int :rtype: int """ if n==1: return 9 if n==8: return 475 high=pow(10,n)-1 low=high//10 for i in range(high,low,-1): pal= int(str(i)+str(i)[::-1]) j=high while j*j>=pal: if pal%j==0: return pal%1337 j-=1
c++代码:
#include#include using namespace std;class Solution { public: int largestPalindrome(int n) { if(n==1) return 9; int high=pow(10,n)-1; int low=high/10; for (int i=high;i>low;i--) { long pal=getPal(i); int j=high; while(pal/j<=j) { if(pal%j==0) { return pal%1337; } j--; } } } long getPal(int n) { string n_reverse=to_string(n); reverse(n_reverse.begin(),n_reverse.end()); //转换为char* return atol((to_string(n)+n_reverse).c_str()); }};
解法2:
打表法??? 解法3: 各种数学推倒,很难看不懂。总结:
使用atoi()
系列函数的时候,需要先把字符串转化为char*,用c_str()
在标准库函数<stdlib.h>。 现在的解法第比较慢的,较快的解法我不会。。。 转载地址:http://krlcn.baihongyu.com/