zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    美化博客园
    ansible的安装
    面向对象和类
    函数知识分类
    生成器
    内置函数_old
    迭代器
    装饰器
    Hadoop——MapReduce
    Hadoop——HDFS
  • 原文地址:https://www.cnblogs.com/silence-cnblogs/p/6845706.html
Copyright © 2011-2022 走看看