• 【LeetCode】9. Palindrome Number (2 solutions)


    Palindrome Number

    Determine whether an integer is a palindrome. Do this without extra space.

    click to show spoilers.

    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.

    解法一:

    求出x的逆序数y,判断两者是否相等即可。

    时间复杂度:O(k),k为x的位数

    class Solution {
    public:
        int reverse(int x) {
            long long y = 0;
            int num = x;
    
            while(num)
            {
                y = y*10 + num%10;
                num /= 10;
            }
            return y;  //valid
        }
        
        bool isPalindrome(int x) {
            if(x < 0)
                return false;
            if(x == reverse(x))
                return true;
            else
                return false;
        }
    };

    解法二:

    转为string类型,然后首尾指针逐字符比较。

    时间复杂度:O(k),k为x的位数

    class Solution {
    public:
        bool isPalindrome(int x) {
            string xstr = to_string(x);
            for(int i=0, j=xstr.size()-1; i < j; i ++, j --)
            {
                if(xstr[i] != xstr[j])
                    return false;
            }
            return true;
        }
    };

  • 相关阅读:
    oracle查看所有角色
    jQuery 异步提交表单实例解析
    oracle查看用户系统权限
    js中日期操作大全
    oracle 查询用户下所有表
    JS语法字典
    JS定时器例子讲解
    开源软件
    rpm的使用
    lvs+keepalived和haproxy+heartbeat区别
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4177082.html
Copyright © 2020-2023  润新知