Swift LeetCode 系列之9: palindrome-number

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

palindrome-number: 回文数 , 简单理解就是对称数

解决: 每次取到第一个数和最后一个数进行对比, 对比后把首尾去掉,直到原数据为0

class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        
        if x < 0 {
             return false
        }
        
        var div = 1
        var num = x
        while (num / div >= 10) {
            div = div * 10
        }
        
        while(num != 0) {
            let left = num / div
            let right = num % 10 
            if left != right {
                return false
            }
            num = (num - left * div) / 10
            div = div / 100
        }
        return true
        
    }
}
class Solution {
    func isPalindrome(_ x: Int) -> Bool {
        guard x >= 0 else {
            return false
        }
        var num = String(x)
        while(num.count > 1) {
            guard let first = num.first else { return false }
            guard let last = num.last else { return false }
            guard first == last else { return false }
            num.removeFirst()
            num.removeLast()
        }
        return true
    }
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/99f3a6a7bb76
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞