[Swift]LeetCode9. 回文数 | Palindrome Number
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9697895.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
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:
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 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 }