3.回文数-Palindrome Number

LeetCode Link: https://leetcode.com/problems/palindrome-number/

Description:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判断一个整数是否是回文数(从左往右和从右往左读都是一样的整数)

Example:

//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.

Tints:

1.负数不可能是回文数
2.将给出的数与反转后的数进行比较,关于如何反转整数

Solution:

import Foundation

func isPalindrome(_ x: Int) -> Bool {
    guard x >= 0 else { return false }
    
    var temp = x
    var result = 0
    while (temp != 0) {
        result = result * 10 + temp % 10
        temp /= 10
    }
    return result == x
}

Runtime: 32 ms, faster than 95.63% of Swift online submissions for Palindrome Number.

Memory Usage: 21.1 MB, less than 5.55% of Swift online submissions for Palindrome Number.

Analyze:关键是如何反转整数

你可能感兴趣的:(3.回文数-Palindrome Number)