zoukankan      html  css  js  c++  java
  • 【LC_Lesson3】---回文数的判别

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

    示例 1:

    输入: 121
    输出: true

    示例 2:

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

    示例 3:

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

    一. 题目分析

    根据题目的要求,有两种解法:

    1. 将数据转换为字符串,然后从首尾方向开始判别每个字符是否相等

    2. 分析回文数的数学特性,进行判断

      1) 负数因为负号的存在 一定不是回文数

      2) 如果正数为回文数,则每一位数据反转之后,最终的数值应该和原值相等,这点其实又和前一篇介绍的整数反转联系到了一起。

    二. 代码实现

    c++实现

     1 bool Solution::IsPalindrome(int num)
     2 {
     3     long long ans = 0;
     4     int temp = num;
     5     if (temp < 0)            
     6     {
     7         printf("%d is not a Palindrome
    ",num);
     8         return false;
     9     }
    10     while (temp)
    11     {
    12         int pop = temp % 10;
    13         ans = ans*10 + pop;
    14         temp = temp / 10;
    15     }
    16     if (ans != num)
    17     {
    18         printf("%d is not a Palindrome
    ",num);
    19         return false;
    20     }
    21     printf("%d is a Palindrome
    ",num);
    22     return true;
    23 }

    经验贴士:

      1. 在上传leetcode实现时,有被提示,数据溢出。可能是因为某些数据反转之后,会发生溢出的状况,由于我们默认输入的数据为int型,因此反转之后数据我们使用long long型来存储这个反转结果,以避免溢出发出,进而实现我们前后数据的比较,代码可执行通过

      2. 在发生数据反转的时候,一定要把溢出考虑在内,否则你的程序执行是会报错的,这是绝对不允许的。

    python实现:

     1 class Solution():
     2     def IsPalindrome(num:int) -> bool:
     3         if num < 0:
     4             print("%d not a Palindrome" % num)
     5             return False
     6         ans = 0
     7         temp = num
     8         while temp:
     9             pop = temp%10
    10             ans = ans*10 + pop
    11             temp = temp//10
    12         print (ans)
    13         if num!=ans:
    14             print("%d is not a Palindrome" % num)
    15             return False
    16         print("%d is a Palindrome" % num)
    17         return True
    18 
    19 Solution.IsPalindrome(121)

    经验贴士:

      1.  在python实现的过程中,更多的参考了之前整数反转的解法,整体不难

    
    
  • 相关阅读:
    BestCoder6 1002 Goffi and Squary Partition(hdu 4982) 解题报告
    codeforces 31C Schedule 解题报告
    codeforces 462C Appleman and Toastman 解题报告
    codeforces 460C. Present 解题报告
    BestCoder3 1002 BestCoder Sequence(hdu 4908) 解题报告
    BestCoder3 1001 Task schedule(hdu 4907) 解题报告
    poj 1195 Mobile phones 解题报告
    二维树状数组 探索进行中
    codeforces 460B Little Dima and Equation 解题报告
    通过Sql语句控制SQLite数据库增删改查
  • 原文地址:https://www.cnblogs.com/szhb-5251/p/11749142.html
Copyright © 2011-2022 走看看