Amazon Interview Question
Software Engineer / DevelopersBadal actually its quite easy
public boolean checkPalindrome (int num)
{
int reverse =0;
while(num)
{
int quotient = num/10;
reverse = reverse * 10 + num %10;
num = quotient;
}
if (num == reverse)
{
return true;
}
else
{
return false;
}
}
to Abid:
wouldn't it be easier to first convert the number into a String and then reverse it and then check whether the reverse is equal? It might lower the chance of getting it wrong in your first try unless you're a math guru.
In both the codes given above, there is no code to handle any kind of exception that might occur while check for pallindrome. What if we have a number like 12a21 ?
Badal's code will throw a NumberFormatException in that case which can be handled like
catch(NumberFormatException e){
e.printStackTrace();
return false;
}
while Abid's code will fail straightaway. So i think we must convert it first into a string before checking for pallindrome since we also have to check the exceptional cases.
Please tell me if I'm missing something here.
We reverse the bits of the original number into a new number and test for equality. The reverse is done similar to reversal of a linked list, by removing the LSB from the first followed by a right shift, and adding to the LSB of the second followed by a left shift.
bool isPalindrome(int x)
{
int n=x, m=0;
while(n>0)
{
m = (m<<1) | (n&1);
n = (n>>1);
}
return x==m;
}
Thanks!
This is the solution in Java.
- badalrocks January 06, 2009package com.badal.careercup;
public class IntPalindrome {
private boolean isPalindrome(int n){
String test=Integer.toString(n);
if(test.charAt(0)!=test.charAt(test.length()-1)){
System.out.println("First and last digits are not same. The number is not a palindrome. ");
return false;
}
String firsthalf=test.substring(0,test.length()/2);
//System.out.println("First Half is: "+firsthalf);
String secondhalf;
if(test.length()%2==0){
secondhalf=test.substring(test.length()/2, test.length());
}else{
secondhalf= test.substring(test.length()/2+1, test.length());
}
StringBuffer sb=new StringBuffer(secondhalf);
sb=sb.reverse();
String reverseSecondhalf=sb.toString();
//System.out.println("Reverse Second Half is: "+reverseSecondhalf);
if(firsthalf.equals(reverseSecondhalf)){
return true;
}
else{
return false;
}
}
public static void main(String [] args){
IntPalindrome obj=new IntPalindrome();
if(obj.isPalindrome(123213)){
System.out.println("The number is a palindrome.");
}else{
System.out.println("The number is not a palindrome.");
}
}
}