Print Palindrome Numbers in Given Range using Java

There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to print Palindrome Numbers in Given Range using Java.

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat hard question you might get asked in an interview so make sure to practice it on your own after reading this article.

 

What’s The Approach?

 

  • Let’s consider input number n till range max Therefore if the reverse of n is similar to n we’ll print true otherwise we’ll print false.

 

  • We will create a separate function isPalindrome to return the reverse of input min.

 

  • Create a reverse variable rev, we will multiply it by 10 & perform a modulo operation with 10

 

  • If the function returns 1 then we’ll print the number, otherwise, we’ll pass.

 

  • The above instructions will keep executing till we reach the end of the input range. So we’ll create a for loop, starting and ending with our given range incremented by 1 each time.

 

Also Read: Multiply Integers Using Russian Peasant Algorithm in C++

 

Java Program To Print Palindrome Numbers in Given Range

 

Input:

100, 200

 

Output:

101 111 121 131 141 151 161 171 181 191 

 

// Java Program to print all
// palindromes in a given range

class TechDecodeTutorials
{
    
    // A function to check
    // if n is palindrome
    static int isPalindrome(int n)
    {
        
        // Find reverse of n
        int rev = 0;
        for (int i = n; i > 0; i /= 10)
            rev = rev * 10 + i % 10;
            
        // If n and rev are same,
        // then n is palindrome
        return(n == rev) ? 1 : 0;
    }
    
    // prints palindrome between
    // min and max
    static void countPal(int min, int max)
    {
        for (int i = min; i <= max; i++)
            if (isPalindrome(i)==1)
                System.out.print(i + " ");
    }
    
    // Driver Code
    public static void main(String args[])
    {
        countPal(100, 200);
    }
}


 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *