志,敢教日月换新天。为有牺牲多壮

[Swift]LeetCode9. 回文数 | Palindrome Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9697895.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 }
复制代码

 

posted @   为敢技术  阅读(517)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示
哥伦布
09:09发布
哥伦布
09:09发布
3°
多云
东南风
3级
空气质量
相对湿度
47%
今天
中雨
3°/15°
周三
中雨
3°/13°
周四
小雪
-1°/6°