LoginSignup
1
2

More than 5 years have passed since last update.

面接で絶対に押さえておきたいアルゴリズム問題(3)

Last updated at Posted at 2017-06-27

問題:Palindrome Number

渡された入力値が、後ろから読んでも前から読んでも同じ整数だった場合、trueを返せよ。
同じでなかった場合はfalseを返す。

例:

input: 1234321 
return: true

input: 6776
return: true

input 14356
return: false

ヒント:

入力値を全部逆さまに並べて、最初の入力値と比較するとよし。

解答:


    func isPalindrome(_ x: Int) -> Bool {

    let originalX = x
    var xNew = abs(x)

    var reversed = 0

        while xNew > 0 {
            reversed = reversed * 10 + xNew % 10
            xNew = xNew / 10
        }

        if reversed > Int(Int32.max) || reversed < Int(Int32.min) {
            reversed = 0
        }

    return reversed == originalX
}
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2