[Swift]LeetCode9. 回文数 | Palindrome Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-eutkcjrs-me.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

Example 1:github

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:spa

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

Follow up:code

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


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

示例 1:get

输入: 121
输出: true

示例 2:博客

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

示例 3:

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

 
 1 class Solution {
 2     func isPalindrome(_ x: Int) -> Bool {
 3         // 特殊状况:
 4         // 如上所述,当 x < 0 时,x 不是回文数。
 5         // 一样地,若是数字的最后一位是 0,为了使该数字为回文,
 6         // 则其第一位数字也应该是 0
 7         // 只有 0 知足这一属性
 8         var num:Int=x
 9         if num < 0 || (num % 10 == 0 && num != 0)
10         {
11             return false        
12         }
13         
14         var revertedNum:Int=0
15         while(num > revertedNum)
16         {
17             revertedNum = revertedNum*10 + num%10
18             num /= 10
19         }
20         // 当数字长度为奇数时,咱们能够经过 revertedNumber/10 去除处于中位的数字。
21         // 例如,当输入为 12321 时,在 while 循环的末尾咱们能够获得 x=12,revertedNumber=123
22         // 因为处于中位的数字不影响回文(它老是与本身相等),因此咱们能够简单地将其去除。 
23         return num == revertedNum || num==revertedNum/10
24     }
25 } 

52ms

 1 class Solution {
 2     func isPalindrome(_ x: Int) -> Bool {
 3         if x < 0 {return false}
 4         var reversed = 0, temp = x
 5         while temp != 0 {
 6             reversed = reversed * 10 + temp % 10
 7             temp /= 10
 8         }
 9         return reversed == x
10     }
11 }
相关文章
相关标签/搜索