[LeetCode] #9 Palindrome Number

#9 Palindrome Number

Question

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.

Thinking

此題解法與#7 Reverse Integer類似,至於題目所提到的extra space,從討論串中我們得知它通常代表O(n)的額外空間,例如:儲存多個值的陣列;同理no extra space代表O(1)的額外空間,例如:單一值的變數

My C# Solution

public class Solution {
    public bool IsPalindrome(int x) {
        if (x < 0) return false;
        int clonex = x;
        int result = 0;
        while (clonex != 0)
        {
            var val = clonex % 10;
            result = result * 10 + val;
            clonex = clonex / 10;          
        }
        return (result == x); 
    }
}