题目描述
20位的整数在swift中如何比较大小?
题目来源及自己的思路
https://leetcode-cn.com/probl...
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
extension Character{
func unicodeValue() -> Int{
for c in String(self).lowercased().unicodeScalars{
return Int(c.value)
}
return 0
}
}
func myAtoi(_ str: String) -> Int {
let min = -2147483648, max = 2147483647
let filteredStr = str.trimmingCharacters(in: CharacterSet(charactersIn: " "))
var integerString = ""
var foundSign = false
if filteredStr.count>0 {
for c in filteredStr{
if (c == "+" || c == "-") && !foundSign{
integerString += String(c)
foundSign = true
}
else if c.unicodeValue() >= 48 && c.unicodeValue() <= 57{
integerString += String(c)
}
else{
return Int(integerString) ?? 0
}
}
let res = Int(integerString) ?? 0
return res >= min && res <= max ? res : (res < min ? min : (res > max ? max :res))
}
return 0
}
你期待的结果是什么?实际看到的错误信息又是什么?
当输入str = 20000000000000000000时,
预期:2147483647;实际输出0.