Created
June 12, 2019 07:58
-
-
Save wangdu1005/eb7786fb8884121b4ea6fe5d1c589d95 to your computer and use it in GitHub Desktop.
We divided the input by 10 for every iteration, so the time complexity is O(log10(n)) Space complexity : O(1).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func isPalindrome(_ x: Int) -> Bool { | |
return self.reverseWay(x) | |
} | |
// Recommanded | |
func reverseWay(_ x: Int) -> Bool { | |
if x < 0 { return false } | |
if x < 10 { return true } | |
var number = x | |
var reverseNumber = 0 | |
while number > 0 { | |
let reminder = number % 10 | |
reverseNumber = reverseNumber * 10 + reminder | |
number = number / 10 | |
} | |
return x == reverseNumber | |
} | |
func firstEndWay(_ x: Int) -> Bool { | |
if x < 0 {return false} | |
if x < 10 {return true} | |
var a:Int = x | |
var num:Int = 1; | |
while (a / num / 10 > 0) { | |
num = num * 10 | |
} | |
while(a > 0) { | |
let first:Int = a / num | |
let end:Int = a % 10 | |
if first == end { | |
a = (a - first * num) / 10 | |
num = num / 100 | |
}else { | |
return false | |
} | |
} | |
return true | |
} | |
func stringWay(_ x: Int) -> Bool { | |
if x >= 0 && x < 10 { | |
return true | |
} | |
let string = "\(x)" | |
var startIndex = string.startIndex | |
var endIndex = string.endIndex | |
endIndex = string.index(before: endIndex) | |
while startIndex < endIndex { | |
if string[startIndex] != string[endIndex] { | |
return false | |
} | |
startIndex = string.index(after: startIndex) | |
endIndex = string.index(before: endIndex) | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment