An idea about reversing the Integer


  • 0
    M

    Reversing the whole Integer may cause overflow. So I only reversed half of it.

    This is my code in Java :

    public class Solution {
    public boolean isPalindrome(int x) {
    	if (x < 0) {
    		return false;
    	}
    
    	if (x < 10) {
    		return true;
    	}
    
    	int len = numDigits(x);
    
    	int highHalf = x / (int) Math.pow(10, (len + 1) / 2);
    	int lowHalf = reverse(x, len / 2);
    	return highHalf == lowHalf;
    }
    
    public int numDigits(int x) {
    	int len = 0;
    	while (x > 0) {
    		x /= 10;
    		len++;
    	}
    	return len;
    }
    
    public int reverse(int x, int numDigits) {
    	int y = 0;
    	for (int i = 0; i < numDigits; i++) {
    		y = y * 10 + x % 10;
    		x /= 10;
    	}
    
    	return y;
    }
    

    But the performance is low(about 572ms). Hope someone can optimize it in this way.


  • 0
    S

    you can simply reconstruct the whole number and compare it with the original, there is not needs to split it in half.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.