Salesforce Interview Question

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

Interview Answers

Anonymous

Mar 20, 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

Dec 13, 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

Feb 9, 2020

How is 2020 a palindrome?

Anonymous

Mar 2, 2016

The point is to use math, as explicitly said.

Anonymous

Jan 5, 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.