Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
Example:
Input: N=101110
Output: 101101
Approach
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class LargestPalindrom {public static void main(String[] args) {List<Integer> listP = new ArrayList<Integer>();preCalPalindrom(listP);int n = 101110;int ans = 0;int len = listP.size();// find the greatest number// which is less than n and palindromefor (int i = len - 1; i >= 0; i--) {if (listP.get(i) < n) {ans = listP.get(i);break;}}System.out.println(ans);}// Calculate all palindromeprivate static void preCalPalindrom(List<Integer> listP) {// store all palindrome of// number which are product of// 2 three digit numbersfor (int i = 100; i < 1000; i++) {for (int j = 100; j < 1000; j++) {int x = i * j;if (isPalindrome(x))listP.add(x);}}// sort themCollections.sort(listP);}private static boolean isPalindrome(int n) {int num = n;int rev = 0;while (n > 0) {rev = rev * 10 + n % 10;n = n / 10;}if (rev == num)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for//palindromebool isPalindrome(int n){int num=n;int rev=0;while(n>0){rev=rev*10+n%10;n=n/10;}if(rev==num)return true;return false;}int main(){vector<int> res;//store all palindrome of//number which are product of//2 three digit numbersfor(int i=100;i<1000;i++){for(int j=100;j<1000;j++){int x=i*j;if(isPalindrome(x))res.push_back(x);}}int len=res.size();//sort themsort(res.begin(),res.end());int n=101110;int ans;//find the gretest number//which is less than n and//palindromefor(int i=len-1;i>=0;i--){if(res[i]<n){ans=res[i];break;}}cout<<ans<<"\n";return 0;}
No comments:
Post a Comment