palindrome in java middle element code example

Example 1: generate palindrome java

//This function generates a palindrom by recursively reversing a String,
//recursively add it and checks if it's a palindrom

public static String generatePalindrom(String s) {
	return s.equals(reverseString(s)) ? s
				: generatePalindrom(String.valueOf(Integer.parseInt(s) + Integer.parseInt(reverseString(s))));
}

public static String reverseString(String s) {
	return s.length() == 1 ? s : s.charAt(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
}

Example 2: palindrome in java

package com.candidjava; import java.util.Scanner; public class PalindromeUptoN{	public static void main(String[] args)	{		int n, b, rev = 0;		Scanner sc = new Scanner(System.in);		System.out.println("Enter the Palindrome No N:");		int N = sc.nextInt();		System.out.print("Palindrome numbers from 1 to N:");		for (int i = 1; i <= N; i++)		{			n = i;			while (n > 0)			{				b = n % 10;				rev = rev * 10 + b;				n = n / 10;			}			if (rev == i)			{				System.out.print(i + " ");			}			rev = 0;		}	} }

Tags:

Java Example