DEV Community

Jagadeesh
Jagadeesh

Posted on

Integer Palindrome

PALINDROME INTEGER

KEYWORDS / QUESTIONS
num % 10 - Get right most number. num / 10 - Remove right most number.

NOTES

  • Number palindrome.
  • A palindrome is a word, phrase, number, or sequence of words that reads the same backward as forward. The straightforward solution would be to convert numbers to string and use the PalindromeString approach.
  • There are two most important things to remember.
  • To get the most right number, we can do 'num % 10'.
  • To remove most right number, we can do 'num / 10'.
  • Both will work for any numbers.

Steps:

  1. Loop through num till it becomes zero.
  2. Get the most right number.
  3. First multiply by 10. Later concat with the rightmost number(do not add)
  4. Remove most right number from num.
  5. If reversed version and original are equal so it's a palindrome

Time Complexity: O(n)

  • 'remainder = num % 10;' here when num will become less than 10 expression will return that number so that's how program copying last(first) number
  • 'num = num / 10;' here when num will become less than 10 expression will make it 0 and program will exit from the loop

Implementation

package com.playground;

public class PalindromeInteger {

    public static boolean isPal(int num) {
        int copyOfOriginal = num;
        int reversedNumber = 0;
        int remainder;

        // 1. Loop through num till it becomes zero.
        while (num > 0) {
            // 2. Get most right number.
            remainder = num % 10;

            // 3. First multiply by 10. Later concat with right most number(do not add)
            reversedNumber = (reversedNumber * 10) + remainder;

            // 4. Remove most right number from num.
            num = num / 10;
        }

        // 5. If reversed version and original are equal so it's palindrome
        return reversedNumber == copyOfOriginal;
    }
}
Enter fullscreen mode Exit fullscreen mode

Test

package com.playground;

import com.playground.PalindromeInteger;
import org.junit.Assert;
import org.junit.Test;

public class PalindromeIntegerTest {

    @Test
    public void withValidPalInt() {
        Assert.assertEquals(PalindromeInteger.isPal(242), true);
    }

    @Test
    public void withNonPalInt() {
        Assert.assertEquals(PalindromeInteger.isPal(243), false);
    }

    @Test
    public void withSingleInt() {
        Assert.assertEquals(PalindromeInteger.isPal(2), true);
    }

    @Test
    public void withTwoInt() {
        Assert.assertEquals(PalindromeInteger.isPal(40), false);
    }

    @Test
    public void withTwoPalInt() {
        Assert.assertEquals(PalindromeInteger.isPal(44), true);
    }

}
Enter fullscreen mode Exit fullscreen mode

SUMMARY
There are two most important things to remember.
To get the most right number, we can do 'num % 10'.
To remove most right number, we can do 'num / 10'.
Both will work for any numbers.

Top comments (0)