Bloomberg interview question

Write a function to check whether an integer is a palindrome without using arrays.

Interview Answers

Anonymous

Jan 28, 2015

Just reverse the number and compare with the original one. Note, that it actually depends on the radix base, whether the number is a palindrome (in that base) or not. bool is_palindrome(const unsigned n, const unsigned radix = 10) { if (radix <= 0) return false; unsigned x = n; unsigned reverse = 0; while (x != 0) { reverse *= radix; reverse += x % radix; x /= radix; } // 0 is considered a palindrome here // (reads the same way from both sides after all) return n == reverse; }

4

Anonymous

Sep 13, 2015

class practice{ public static void main(String args[]){ System.out.println(pal(987789)); } public static boolean pal (int a){ if(a/10 == 0){ return true; } int unit=a%10; int d=a; int count=0; while(d/10>0){ d=d/10; count++; } if(d%10==unit){ return pal((a-unit*(int)Math.pow(10.0,count))/10); } return false; } }