【leetcode】009-Palindrome Number

  本篇博客解析 009-Palindrome Number


 

一、题目

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

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

  示例:

 

二、分析

  根据回文数的定义,可知所有负数都不是回文数,0 是回文数。实际上我们只需要判断正数是否是回文数。

  再根据回文数的性质,我们可以对传入的参数做 reverse 处理,然后对比结果和参数,如果相等,则是回文数。

 

三、代码

 1 int reverse(int x)
 2 {
 3     int result = 0;
 4 
 5     while (x)
 6     {
 7         if (INT_MAX / 10 < result)
 8         {
 9             return 0;
10         }
11 
12         result = result * 10 + x % 10;
13 
14         x /= 10;
15     }
16 
17     return result;
18 }
19 
20 bool isPalindrome(int x)
21 {
22     if (x < 0)
23         return false;
24     else if (x == 0)
25         return true;
26     else
27         return (reverse(x) == x);
28 }

 

posted @ 2020-06-14 07:32  Albert-陌尘  阅读(110)  评论(0编辑  收藏  举报