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.

1.枚举

  1. 利用两个for循环枚举两个三位数相乘
  2. 判断相乘的乘积是否是回文整数(将数字倒置判断是否等于原数字
  3. 动态刷新最大回文整数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

//自定义判断回文数字func函数
int func(int num){
int raw = num, reverse = 0;
while(num){
//(1)将x值的最后一位放入reverse中,并且向前移动一位
reverse = reverse * 10 + num % 10;
//(2)去掉x值的最后一位
num /= 10;
}
return raw == reverse;
}

int main(){
int ans = 0;
//1.利用两个for循环枚举两个三位数相乘
for(int i = 0; i < 1000; i++){
for(int j = i; j < 1000; j++){
//2.判断相乘的乘积是否为回文数字
if(func(i * j)){
//3.动态刷新最大回文数字
ans = max(ans, i * j);
}
}
}
cout << ans << endl;
return 0;
}
//时间复杂度:O(n*n)

2.回文数判断

1
2
3
4
5
6
7
8
9
10
11
//回文数字的判断
int func(int num){
int raw = num, reverse = 0;
while(num){
//(1)将num值的最后一位放入reverse中,并且向前移动一位
reverse = reverse * 10 + num % 10;
//(2)去掉num值的最后一位
num /= 10;
}
return raw == reverse;
}