My answer: Not good one. Got impacted by the reverse-string question. Many cases were not taken into account at 1st step, like -2147483648(-2^31), 0, 10. Should have verified code using such cases.
Better solution has been posted below, which doesn't have to handle case where number is negative, and can be extended if we want to reverse Long
class Solution { public int reverse(int x) { int sign = 1; long maxAbsoluteIntValue = Long.valueOf(Integer.MAX_VALUE); if (x < 0) { sign = -1; maxAbsoluteIntValue = Math.abs(Long.valueOf(Integer.MIN_VALUE)); } else if (x == 0) { return 0; } while ( x % 10 == 0) { x /= 10; } String rawNumStr = String.valueOf(x); String numStr = rawNumStr; if (sign < 0) { numStr = rawNumStr.substring(1, rawNumStr.length()); } int i = 0; char temp = ' '; char[] numArray = numStr.toCharArray(); while (i < numArray.length/2) { temp = numArray[i]; numArray[i] = numArray[numArray.length - 1 - i]; numArray[numArray.length - 1 - i] = temp; i ++; } String reverseStr = String.valueOf(numArray); if (Long.valueOf(reverseStr) > maxAbsoluteIntValue) { return 0; } else { return Integer.valueOf(reverseStr) * sign; } } }
Better solution:
public class Solution { /** * @param n the integer to be reversed * @return the reversed integer */ public int reverseInteger(int n) { int reversed_n = 0; while (n != 0) { int temp = reversed_n * 10 + n % 10; n = n / 10; if (temp / 10 != reversed_n) { // if overflow reversed_n = 0; break; } reversed_n = temp; } return reversed_n; } }
No comments:
Post a Comment