zoukankan      html  css  js  c++  java
  • 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
    知识共享,欢迎转载。
  • 相关阅读:
    【每日一题】 UVA
    【每日一题】 UVA
    【每日一题】 UVA
    【每日一题】 UVA
    【每日一题】UVA
    【每日一题】 uva-232 模拟+输出要求很严格
    【每日一题】 UVA
    MYSQL约束
    数据库,SQL分类
    类加载器&反射&模块化
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616321.html
Copyright © 2011-2022 走看看