Is my algorithm using extra space


  • 0
    L

    There are a lot of ways to achieve the solution, but the difficulty is to do without extra space.
    My algorithm uses one integer "y" only, to store the reversed right half of original number "x". If x==y, then it's palindrome.
    Any improvement?

    public class Solution {
        public boolean isPalindrome(int x) {
    		// negative is not
    		if(x<0){
    		    return false;
    		}
    		for(int y=0;x>=y;x/=10){
    		    // even digits case like 1001 or 0
    			if(x==y){
    				return true;
    			}
    			y = y*10+x%10;
    			if(y==0){
    			    // 010 is not palindrome
    			    return false;
    			}
    			// odd digits case like 101 or 1
    			if(x==y){
    				return true;
    			}
    		}
            return false;
        }
    }

  • 0
    S

    Pay attention to "Writing code? Select a code block and click on the button to preserve code formatting.” above text editor.


  • 0
    S

    Thanks for updating code formatting.


Log in to reply
 

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