133k views
3 votes
// Problem 7: isPalindrome (10 points) // Return 1 if string s is palindrome. // Parse through the string to check if 1st char==last char, 2nd char == (last-1) char, and so on.. // Return 1 if string is palindrome. Return 0 if string is not palindrome. // A palindrome is a sequence of characters which when reversed, is the same sequence of characters. // Palindrome string examples: rotor, noon, madam // Note: you may use reverseOneString() here but it is not necessary to use it.

User Giawa
by
5.6k points

1 Answer

1 vote

Answer:

// program in java.

// library

import java.util.*;

// class definition

class Main

{

// recursive function to check palindrome

public static int isPalindrome(String s)

{

// find length of String

int len=s.length();

for(int i=0;i<len;i++)

{

// compare first with last, second with second last and so on

if(s.charAt(i)!=s.charAt(len-i-1))

{

// if not palindrome return 0

return 0;

}

}

// if palindrome return 1

return 1;

}

// main method of the class

public static void main (String[] args) throws java.lang.Exception

{

try{

// object to read input

Scanner scr=new Scanner(System.in);

System.out.print("Enter a string:");

// read string from user

String s =scr.nextLine();

// call function to check palindrome

int res=isPalindrome(s);

// if string is palindrome

if (res==1)

System.out.println("Given String is a palindrome");

else

// if string is not palindrome

System.out.println("Given String is not a palindrome");

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Read a string from user and assign it to variable "s".Call the method isPalindrome() with parameter "s".In this function find the length of the string.Then compare first character with last and second with second last and so on.If the string is palindrome then it will return 1 else it will return 0.

Output:

Enter a string:rotor

Given String is a palindrome

User Amir Saniyan
by
6.2k points