Last active
April 9, 2025 11:25
-
-
Save shricodev/46048aed118380d6cbfc36c0e46f55d2 to your computer and use it in GitHub Desktop.
Test Case Passing: 10/632
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: | |
| 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; | |
| } | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem Link: https://leetcode.com/problems/find-the-largest-palindrome-divisible-by-k/