Determine whether an integer is a palindrome. Do this without extra space.
Some hints:Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
There are two solutions for this problem: one is reverse the integer can then compare. And notice that there is no need to handle overflow since if overflow happens it cannot be a palindrome number. Another solution is to extract left most number and right most number each time and then compare.
C++ Code 1:
/* * func: is_palindrome * goal: to check if the number is in palindrome format * @param x: input integer x * return: whether the integer is palindrome */ bool is_palindrome(int x){ //If x is a negative number, return false if(x < 0){ return false; } //Reverse the integer and check int reverse = 0; int tmp_x = x; while(tmp_x != 0){ reverse = reverse * 10 + tmp_x % 10; tmp_x /= 10; } return reverse == x; }
C++ Code 2:
/* * func: is_palindrome * goal: to check if the number is in palindrome format * @param x: input integer x * return: whether the integer is palindrome */ bool is_palindrome(int x){ //If x is a negative number, return false if(x < 0){ return false; } int divisor = 1; //Compute the largest divisor to get the left //side number in further step while(x / div >= 10){ divisor *= 10; } //Compare each left number and right number while(x != 0){ int left = x / div; int right = x % 10; if(left != right){ return false; } //Update x x = (x % divisor) / 10; //Update divisor divisor /= 100; } return true; }
The two solutions showed similar performance. Solution 1 used less space but a little bit more time(784ms vs 740ms).
Python Code 1:
# func: check if the integer is a palindrome number # @param x: input integer # @return: True or False def is_palindrome(x): #If x is negative if x < 0: return False else: reverse = 0 tmp = x while tmp != 0: reverse = reverse * 10 + tmp % 10 tmp /= 10 return x == reverse
Python Code 2:
# func: check if the integer is a palindrome number # @param x: input integer # @return: True or False def is_palindrome(x): #If x is negative if x < 0: return False else: #Compute the largest divisor divisor = 1 while x / divisor >= 10: divisor *= 10 #Compute the left number with its corresponding right number while x != 0: left = x / divisor right = x % 10 if left != right: return False #Update x and divisor x = (x % divisor) / 10 divisor /= 100 return True
However, in Python, solution 1 used less time to complete (1868ms vs 1944ms).
No comments:
Post a Comment