• 9. Palindrome Number QuestionEditorial Solution


    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.


    每次区首尾两位进行比较,然后再去掉首尾两位循环。

    #include <iostream>
    #include <vector>
    #include <set>
    #include <algorithm>
    #include <string>
    #include <sstream>
    #include <cstring>
    #include <cmath>
    using namespace std;
    
    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0)
            {
                return false;
            }
            //数字长度
            int len = 0;
            int temp = x;
            while(temp != 0)
            {
                temp = temp / 10;
                len++;
            }
            while(x != 0)
            {
                int bottom = x % 10;
                int top = x / (int)pow(10, len - 1);
                if (bottom != top)
                {
                    return false;
                }
                x = (x % (int)pow(10, len - 1)) / 10;
                len -= 2;
            }
            return true;
        }
    };
    
    int main()
    { 
        Solution s;
        cout << s.isPalindrome(123212) << endl;
        return 0;
    }

    Keep it simple!
    作者:N3verL4nd
    知识共享,欢迎转载。
  • 相关阅读:
    MySQL数据库设计规范
    Docker安装redis
    Go-用本地时间解析时间字符串
    Docker安装mysql
    docker安装es
    Json官网文档
    leetcode题目和解答集合
    76. 最小覆盖子串
    165. 比较版本号
    958. 二叉树的完全性检验
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616321.html
Copyright © 2020-2023  润新知