zoukankan      html  css  js  c++  java
  • C++题目:回文数判断

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:

    Input: 121
    Output: true
    

    Example 2:

    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
    

    Example 3:

    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
    

    Follow up:

    Coud you solve it without converting the integer to a string?

    题目来源:https://leetcode.com/problems/palindrome-number/

    先给出自己很一般的算法:

     1 class Solution {
     2 public:
     3 bool isPalindrome(int x) {
     4     if(x>=0&&x<10)
     5         return true;
     6     if (x<0 || x / 10 == 0)
     7         return false;
     8     int countDigit = 0, saveX = x;
     9     int* numArray = new int[12];
    10     bool flag = true;
    11     while (x>=1) {
    12         numArray[countDigit] = x - x / 10 * 10;
    13         countDigit++;
    14         x = x / 10;
    15     }
    16     x = saveX;
    17     for (int i = 0; i<countDigit; i++) {
    18         if (numArray[i] != (int)(x / pow(10, countDigit - i-1)) ){
    19             flag = false;
    20             break;
    21         }
    22         else {
    23             x = x - numArray[i] * pow(10, countDigit - i-1);
    24         }
    25     }
    26     return flag;
    27 }
    28 };

    照例,发现了一个印度小哥的代码很简短:https://leetcode.com/problems/palindrome-number/discuss/5165/An-easy-c%2B%2B-8-lines-code-(only-reversing-till-half-and-then-compare)

     1 class Solution {
     2 public:
     3     bool isPalindrome(int x) {
     4         if(x<0|| (x!=0 &&x%10==0)) return false;
     5         int sum=0;
     6         while(x>sum)
     7         {
     8             sum = sum*10+x%10;
     9             x = x/10;
    10         }
    11         return (x==sum)||(x==sum/10);
    12     }
    13 };

    其实从算法思想上来说,这种思想我也曾想过:把原有数字逆转,然后比较两数字是否相同。但是由于int的限制,很可能会发生正向的数字没有溢出,但是反向的数字就溢出的情况(例如:2147483647,调转过来就溢出了)。而由我上一篇文章中所说(https://www.cnblogs.com/jiading/p/10422265.html),Int溢出后会不断减去或者加上4294967296直至整数范围落在-2147483648 ~ 2147483647内,所以如果直接调转过来可能会导致整数数值的变化,从而导致比较的不正确,所以我没有采用这种办法,而是把整数先一位一位存在数组中,然后一位一位比较,但是这样涉及到比较的次数就较多,而且还使用了数组作为辅助内存。

    而这位小哥的思路就很有价值:他没有把整个数翻转过来,而是只翻转了一半(利用条件:x>sum),所以出while循环时的可能性只有两种:1.x与sum同位数,但是sum>=x(原整数是偶数位情况)  2.sum比x高一位(原整数是奇数位情况)

    而这也导致了最终判断条件是两个((x==sum)||(x==sum/10)

    利用翻转一半的方法,就彻底规避了整数超出范围的情况,非常的机智。

  • 相关阅读:
    iTerm2分屏快捷键
    k8s中运维/测试常用的命令整理(随时更新)
    httpRunner自动化测试用例使用笔记
    Git学习笔记-快速上手(mac系统)
    RBAC权限控制逻辑笔记
    CPS中有关CICD的配置
    LDAP中filter的使用
    Docker初级入门
    C语言 实现 HashTable
    从三个线程 排队打印 , 到 多个线程打印
  • 原文地址:https://www.cnblogs.com/jiading/p/10425425.html
Copyright © 2011-2022 走看看