Java solution without additional variables


  • 0
    V
    public boolean isPalindrome(int x) {
    	return isPalindrome((long)x);
    }
    
    private boolean isPalindrome(long x) {
    	if (x < 0) {
    		return false;
    	}
    	if (x >= 0 && x <= 9) {
    		return true;
    	}
    	x = replaceZeroes(x);
    	
    	while (x > 0) {
    		if (getFirst(x) != getLast(x)) {
    			return false;
    		}
    		x = removeFirst(removeLast(x));
    	}
    	
    	return true;
    }
    
    
    private long replaceZeroes(long x) {
    	if (x < 10) {
    		return x == 0 ? 0xA : x;
    	}
    	return replaceZeroes(x / 10) * 0x10 + (x % 10 == 0 ? 0xA : x % 10);
    }
    
    private long removeFirst(long x) {
    	if (x < 0x10) {
    		return 0;
    	}
    	return removeFirst(x / 0x10) * 0x10 + x % 0x10;
    }
    
    private long removeLast(long x) {
    	return x / 0x10;
    }
    
    private long getFirst(long x) {
    	while (x / 0x10 > 0) {
    		x /= 0x10;
    	}
    	return x;
    }
    
    private long getLast(long x) {
    	return x % 0x10;
    }

  • 0
    P

    You're just using converting local variables into parameters of recursive functions.


Log in to reply
 

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