博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
479. Largest Palindrome Product(python+cpp)(这道题好难我记得..)
阅读量:3702 次
发布时间:2019-05-21

本文共 1648 字,大约阅读时间需要 5 分钟。

题目:

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: 2Output: 987Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Note:

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/

你可能感兴趣的文章
数据结构---字符串
查看>>
ACM---日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
ACM日记
查看>>
4月17日小结
查看>>
4月20日小结
查看>>
4月24日小结
查看>>
4月28日小结
查看>>
5月4日小结
查看>>
第十届山东省省赛总结
查看>>
5月19日小结
查看>>
5月22日小结
查看>>
暑期训练D1
查看>>
暑期训练D2
查看>>
暑期训练D3
查看>>
暑期训练D4
查看>>
暑期训练D5
查看>>
暑期训练D6
查看>>