Array with Palindrome numbers

Check if all the elements in the array are palindromic numbers. If all the elements are palindromes, return 1 otherwise return 0.

Example 1:

Input:
5
111 55555 888 101 100001

Output:
1

Explanation:
A[0] = 111 //which is a palindrome number.
A[1] = 55555 //which is a palindrome number.
A[2] = 888 //which is a palindrome number.
A[3] = 101 //which is a palindrome number.
A[4] = 100001 //which is a palindrome number.
all th numbers are palindrome so return 1

Example 2:

Input: 
2
1000 121
Output: 0

as 1000 is not a palindrome return 0

 




method 1:

The function first iterates through the array using a for loop. For each element in the array, convert it to a string and then create a reverse of this string. Then compare s1 and s2 to check if the original string and the reversed string are equal or not. If they are not equal, then the function immediately returns 0, indicating that the array is not a palindrome array.


Java implementation:

class codemummy
{
public static int palinArray(int[] a, int n)
           {
              for(int i=0;i<n;i++){
                  StringBuffer n1= new StringBuffer(a[i]+"");
                  
                  String s1=n1.toString();
                  String s2=n1.reverse().toString();
                  
                  if(s1.equals(s2)==false){
                      return 0;
                  }
              }
              return 1;
           }
           
};

 Time Complexity:  O(n^2) 
Auxiliary Space: O(1).


c++ implementation:

#include <string>
#include <algorithm>
using namespace std;

int palinArray(int a[], int n) {
    for(int i=0;i<n;i++){
        string s1= to_string(a[i]);
        string s2= s1;
        reverse(s2.begin(), s2.end());
        if(s1 != s2){
            return 0;
        }
    }
    return 1;
}

 Time Complexity:  O(n^2) 
Auxiliary Space: O(1).


python implementation:

def palinArray(a, n):
    for i in range(n):
        s1 = str(a[i])
        s2 = s1[::-1]
        if s1 != s2:
            return 0
    return 1
 Time Complexity:  O(n^2) 
Auxiliary Space: O(1).










No comments

darkmode