Skip to content

Instantly share code, notes, and snippets.

@shricodev
Last active April 9, 2025 11:25
Show Gist options
  • Select an option

  • Save shricodev/46048aed118380d6cbfc36c0e46f55d2 to your computer and use it in GitHub Desktop.

Select an option

Save shricodev/46048aed118380d6cbfc36c0e46f55d2 to your computer and use it in GitHub Desktop.
Test Case Passing: 10/632
class Solution {
public:
string largestPalindrome(int n, int k) {
string maxNum(n, '9');
string result = "";
// Iterate from max possible number to min possible number
for (long long num = stol(maxNum); num >= stol(string(n, '1') + (n > 1 ? "0" : ""); num--) {
string strNum = to_string(num);
// Check if number is palindrome and divisible by k
if (isPalindrome(strNum) && num % k == 0) {
result = strNum;
break;
}
}
return result;
}
// Helper function to check if a number is palindrome
bool isPalindrome(const string& str) {
int left = 0, right = str.size() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
};
@shricodev

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment