题目

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

Example 1:

1
2
Input: 121
Output: true

Example 2:

1
2
3
4
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:

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

Follow up:

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

分析

这是一道比较简单的题目
只要分析出来三个判断就可以

  1. 等于零
  2. 小于零
  3. 大于零

    等于零

    等于零肯定成立,因为零无论正着念,倒着读都是零

    小于零

    有题目知等于零的时候不成立

    大于零

    这是相对来说比较复杂的地方了,设置参数将x倒置比较即可
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    bool isPalindrome(int x) {
    if(x==0)
    {
    return true;
    }
    else if(x<0)
    {
    return false;
    }
    else
    {
    int x1=x;
    int y=0;
    int tmp=0;
    while(x1!=0)
    {
    tmp=x1%10;
    x1=x1/10;
    y=y*10+tmp;
    }
    if(x==y)
    {
    return true;
    }
    else
    {
    return false;
    }

    }


    }