美文网首页Swift LeetCode
Swift LeetCode 系列之9: palindrome-

Swift LeetCode 系列之9: palindrome-

作者: TimberTang | 来源:发表于2017-11-19 22:15 被阅读23次

    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
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift LeetCode 系列之9: palindrome-

        本文链接:https://www.haomeiwen.com/subject/qwzpvxtx.html