0
\$\begingroup\$

Got this question in a technical interview and here is my solution:

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    if (!in.hasNextInt()) {
      System.out.println("not a number!");
    }

    int number = in.nextInt();

    System.out.println(isPalidrom(number));
  }

  private static String isPalidrom(int number) {

    String numberStr = Integer.toString(number);
    String reverseStr = new StringBuilder(numberStr).reverse().toString();

    if (reverseStr.equals(numberStr)) {
      return "palindrome";
    } else {
      return "not palindrome";
    }
  }
}

I was going to solve it with using modulus 10 and decided to do it by reverting the number to integer, was it a good idea?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Some tips:

  • Main is a confusing class name. In your case, an appropriate name might possibly be PalindromeChecker.
  • Your main method would usually be in a separate class called for example Application. That way
    1. PalindromeChecker ends up with a public method for doing the actual check, making the class reusable and
    2. the library and executable parts of your program are properly separated.
  • Why scan for numbers? You are reading from standard input, which by definition is just a byte stream, so you might as well avoid some conversion and just check whether each line that arrives is a palindrome. Number checking could be done elsewhere, if absolutely necessary.
  • The checker function should return a boolean, to avoid mixing logic and presentation. The function also becomes objectively simpler: return reverseStr.equals(numberStr);
  • Look into other ways of converting a string to an integer - they have different pros and cons.
  • Writing up some test methods could expose unexpected behaviour. For example, what does your code do with alternative numbering systems such as Roman or Chinese numerals? Does it handle 10.1 as one integer (101 or 10), two integers (10 and 1), or does it reject it? Does it expand numbers such as 1e5? Does it precompute arithmetic such as 10+1? Converting the int back to a String and comparing it with the original String input might be a useful way of telling whether any automagic conversion has occurred.
  • I believe tell, don't ask applies to the way in is used.

That said, your solution is simple and quick. Given the time & stress of an interview I'd say you nailed it. (Provided it works - I haven't actually run it :)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.