Leetcode 9 - Palindrome Number

朴灿烈づ我的快乐病毒、 2021-12-23 10:07 308阅读 0赞

题目

https://leetcode.com/problems/palindrome-number/

题意

判断一个整数是否是回文数。

Example 1:

  1. Input: 121
  2. Output: true

Example 2:

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

Example 3:

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

思路

author’s blog == http://www.cnblogs.com/toulanboy/

还是一道超级水题。只需把这个数字反转,然后将反转后的数字和原数字对比。如果一致,说明是回文数。

需要注意的地方是:在反转过程中,用int可能会溢出,用long long存储反转数字即可解决。

代码

  1. class Solution { public://author's blog == http://www.cnblogs.com/toulanboy/ bool isPalindrome(int x) { if(x < 0) return false; long long reverseInt = 0; int t = x; while(t){ reverseInt = reverseInt*10 + t%10; t /= 10; } if(x == reverseInt) return true; else return false; } };

运行结果

  1. Runtime: 16 ms, faster than 96.66% of C++ online submissions for Palindrome Number.
  2. Memory Usage: 8.1 MB, less than 80.92% of C++ online submissions for Palindrome Number.

转载于:https://www.cnblogs.com/toulanboy/p/10876349.html

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读