题目4:找出由两个三位数相乘,构成的最大回文数
题目4:找出由两个三位数相乘,构成的最大回文数Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
题目翻译:
一个回文数指的是从左向右和从右向左读都一样的数字。
最大的由两个两位数乘积构成的回文数是 9009 = 91 * 99。
找出由两个三位数相乘,构成的最大回文数。
视频讲解:
https://www.bilibili.com/video/BV1a24y1P7CL/
思路解析及源码参考(C & Python):
**** Hidden Message *****
#include <bits/stdc++.h>
using namespace std;
int ans;
int ri, rj;
bool is_huiwen(int number) {
int rn = number;
int reverse_number = 0;
while (number) {
reverse_number = reverse_number * 10 + number % 10;
number /= 10;
}
return reverse_number == rn;
}
int main() {
for (int i = 100; i <= 999; ++i) {
for (int j = 100; j <= 999; ++j) {
if (i * j > ans && is_huiwen(i * j)) {
ans = i * j;
ri = i;
rj = j;
}
}
}
printf("%d * %d = %d\n", ri, rj, ans);
return 0;
} 原来可以优化{:10_256:}
理论上时间复杂度是相同的,但这种优化提却很好{:10_275:} #include <bits/stdc++.h>
using namespace std;
bool check(int x)
{
string s = to_string(x);
for(int i=0;i<s.length()/2;i++)
if(s!=s) return false;
return true;
}
int main()
{
int ans = 0;
for(int i=100;i<=999;i++)
for(int j=100;j<=999;j++)
if(check(i*j)) ans = max(ans,i*j);
cout<<ans<<endl;
return 0;
} 加油 list1 = []
for i in range(999, 100, -1):
for j in range(999, 100, -1):
num = i * j
str_num = str(num)
if str_num == str_num[::-1]:
list1.append(num)
max_num = max(list1)
for i in range(999, 100, -1):
for j in range(999, 100, -1):
num = i * j
if num == max_num:
print(f'i = {i}, j = {j}, i * j ={num}')
break
学习学习好 4 看看 for a in range(1000, 99, -1):
p = a * 99
if str(p)[::-1] == str(p):
print(p)
break
更正了代码
maxa = maxb = 0
for a in range(1000, 99, -1):
for b in range(1000, 99, -1):
p = a * b
if p > maxa * maxb and str(p)[::-1] == str(p):
maxa = a
maxb = b
print(maxa, maxb, maxa * maxb)
。
/*
Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
题目翻译:
一个回文数指的是从左向右和从右向左读都一样的数字。
最大的由两个两位数乘积构成的回文数是 9009 = 91 * 99。
找出由两个三位数相乘,构成的最大回文数。
*/
#include <bits/stdc++.h>
using namespace std;
int ans;
bool ishuiwen(int n) {
int t, t2, u, ii = 0, iii = 0;
while (n) {
u = n % 10;
t = u;
n /= 10;
}
for (int i = ii - 1; i >= 0; i--) {
t2 = t;
}
for (int i = 0; i < ii; i++) {
if (t2 != t) return false;
}
return true;
}
int main() {
for (int i = 999; i >= 100; i--) {
if (i * 999 < ans) break;
for (int j = 999; j >= 100; j--) {
if (i * j < ans) break;
if (ishuiwen(i * j)) {
if (ans < i * j) ans = i * j;
}
}
}
cout << ans << endl;
return 0;
} 1 。 1 理论上时间复杂度是相同的,但这种优化提却很好 学习学习 test 过来学习下,头脑风暴,学习下编程
页:
[1]
2