zoukankan      html  css  js  c++  java
  • 回文数

    题目来源力扣第九题,链接:https://leetcode-cn.com/problems/palindrome-number

    判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

    示例 1:

    输入: 121
    输出: true
    示例 2:

    输入: -121
    输出: false
    解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
    示例 3:

    输入: 10
    输出: false
    解释: 从右向左读, 为 01 。因此它不是一个回文数。
    进阶:

    你能不将整数转为字符串来解决这个问题吗?


    思路0: 

    1.  题目给出模板为int类型,故默认为是int类型数据。

    2.  如果整数是负数则直接判定false

    3. 如果整数是正整数且只有一位,则直接判定true

    4. 将数据进行反转处理,若与原数据相等,则返回true,反转处理见:https://www.cnblogs.com/yulongzhou/p/12385877.html

    5. 空间复杂度 O(1), 时间复杂度O(log(x))

    代码:

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 class Solution {
     6 public:
     7     bool isPalindrome(int x) {
     8         if (x < 0) return false;
     9         else if (x < 10) return true;
    10         else if (x == reverse(x)) return true;
    11         else return false;
    12     }
    13 
    14 private:
    15     long int reverse(int x) { // 防止数据反转后溢出
    16         long int re_num(0);
    17         while (x != 0) {
    18             re_num *= 10;
    19             re_num += x % 10;
    20             x /= 10;
    21         }
    22         return re_num;
    23     }
    24 };
    25 int main() {
    26     Solution solution;
    27     int eg0(-123), eg1(1), eg2(12321), eg3(12345), eg4(2147483647);
    28     cout << "eg0: " << (bool)solution.isPalindrome(eg0) << endl;
    29     cout << "eg1: " << solution.isPalindrome(eg1) << endl;
    30     cout << "eg2: " << solution.isPalindrome(eg2) << endl;
    31     cout << "eg3: " << solution.isPalindrome(eg3) << endl;
    32     cout << "eg4: " << solution.isPalindrome(eg4) << endl;
    33     return 0;
    34 }

    输出:

    eg0: 0
    eg1: 1
    eg2: 1
    eg3: 0
    eg4: 0

  • 相关阅读:
    Ubuntu将Python3软连接到Python
    装有Ubuntu的硬盘插入到电脑中无法进入
    如何更改鼠标右键新建内容
    HDU 1113 Word Amalgamation
    暴力题,速算24点
    网络营销整合
    灰色预测代码
    灾情巡视C语言代码
    灰色关联度Matlab代码
    BP神经网络代码
  • 原文地址:https://www.cnblogs.com/yulongzhou/p/12388365.html
Copyright © 2011-2022 走看看