[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 }
相關文章
相關標籤/搜索