Bloomberg LP Interview Question
Financial Software Developers@Anonymous: Negative numbers I agree, but can you give an example why an overflow might occur with the above code ?
Agree. On 32-bit machine, int range is –2,147,483,648 to 2,147,483,647. If use this number (–2,147,483,648 or 2,147,483,647), it will overflow.
I think in a recursive way you can solve this problem.
public class InverseInteger {
public static void main(String[] args) {
int n = 1234;
System.out.println(inverse(n));
n = -12345;
System.out.println(inverse(n));
}
private static String inverse(int n) {
if (n != 0)
return "" + (n % 10) + inverse((n < 0 ? n * -1 : n) / 10);
return "";
}
}
Result:
4321
-54321
The program is pretty straightforward, i assume we are talking about positive number, for negative numbers you need more clarification from the interviewer. Also number like '2340' will return '432' - this is should be ok.
- Abdul Malik Mansoor February 18, 2010