-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain2.cpp
68 lines (57 loc) · 1.45 KB
/
main2.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/// Source : https://projecteuler.net/problem=4
/// Author : liuyubobobo
/// Time : 2017-09-23
/***
* If P is a product of two 3 digits, then P must be 6 digits.
* Since P is a palindrome, we can express P as following:
*
* P = 100000x + 10000y + 1000z + 100z + 10y + x
* P = 100001x + 10010y + 1100z
* P = 11 * (9091x + 910y + 100z)
*
* We can see P has a factor 11, which can make us search faster
*/
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution{
public:
int largestPalindromeFrom(int digits){
int smallest = (int)pow(10, digits - 1);
int largest = (int)pow(10, digits) - 1;
int res = -1;
for(int i = largest ; i >= smallest ; i --){
int j, step;
if(i % 11 == 0){
j = largest;
step = 1;
}
else{
j = 990;
step = 11;
}
for(; j >= smallest ; j -= step){
int tres = i * j;
if(tres > res && isPalindrome(tres))
res = tres;
}
}
return res;
}
private:
bool isPalindrome(int num){
int n = num;
int rev = 0;
while(n){
int dig = n % 10;
rev = rev * 10 + dig;
n /= 10;
}
return rev == num;
}
};
int main() {
cout << Solution().largestPalindromeFrom(3) << endl;
return 0;
}