Created
February 1, 2018 17:07
gist for leetcode 479
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int largestPalindrome(int n) { | |
if (n == 1) { | |
return 9; | |
} | |
const int upperBound = static_cast<int>(pow(10.0, (double)n)) - 1; | |
const int lowerBound = upperBound / 10; | |
long palindrome; | |
string numStr, reverseNumStr; | |
for(int num = upperBound; num > lowerBound; num--) { | |
numStr = to_string(num); | |
reverseNumStr = to_string(num); | |
reverse(reverseNumStr.begin(), reverseNumStr.end()); | |
palindrome = stol(numStr + reverseNumStr); | |
//>> check the palindrome is the product of two n-digit number or not | |
for(long p = upperBound; p*p >= palindrome; p--) { | |
if(palindrome % p == 0) { | |
return static_cast<int>(palindrome % 1337); | |
} | |
} | |
} | |
return 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment