LeetCode #9 Palindrome Number

LeetCode #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.

Solution

Approach #1

class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        if x < 0 || (x != 0 && x % 10 == 0) { return false }
        var h = x
        var l = 0
        while h > l {
            l = l * 10 + h % 10
            h /= 10
        }
        return h == l || h == l / 10
    }
}

Time complexity: O(log(x)).

Space complexity: O(1).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6845706.html

posted on 2017-05-12 18:55  Silence_cnblogs  阅读(187)  评论(0编辑  收藏  举报