Salesforce interview question

In java and using math, check if a number is a palindrome.

Interview Answers

Anonymous

20 Mar 2016

boolean isPalindromNumber(int n) { if(n == null) return true; return n == reverseNumber(n); } long reverseNumber(int n) { long rev = 0; while(n != 0) rev = rev * 10 + n % 10; n /= 10; } return rev; }

2

Anonymous

13 Dec 2018

The above doesn't actually work for all cases. For example try 2020. This will solve for all possibilities: public static boolean isPalindromeNumber(int n) { int rev = 0; int orig = n; while(n != 0) { rev = rev * 10 + n % 10; n /= 10; } if(orig % 10 == 0) { rev *= 10; } return (orig == rev); }

Anonymous

9 Feb 2020

How is 2020 a palindrome?

Anonymous

2 Mar 2016

The point is to use math, as explicitly said.

Anonymous

5 Jan 2016

Convert to string and then either (a) revers and compare or (b) using two counters compare characters from both ends until they are not equal or they meet.