前言
实现一个 func myAtoi(_ str: String) -> Int
函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++
中的 atoi
函数)。
函数 func myAtoi(_ str: String) -> Int
的算法如下:
"123" -> 123, "0032" -> 32
)。如果没有读入数字,则整数为 0
。必要时更改符号(从步骤 2 开始)。[−2^31, 2^31 − 1]
,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −2^31
的整数应该被固定为 −2^31
,大于 2^31 − 1
的整数应该被固定为 2^31 − 1
。注意:
' '
。示例 1
输入:str = "42"
输出:42
解释:加粗的字符串为已经读入的字符,插入符号是当前读取的字符。
第 1 步:"42"(当前没有读入字符,因为没有前导空格)
^
第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
^
第 3 步:"42"(读入 "42")
^
解析得到整数 42 。
由于 "42" 在范围 [-231, 231 - 1] 内,最终结果为 42 。
示例 2
输入:str = "-42"
输出:-42
解释:
第 1 步:" -42"(读入前导空格,但忽视掉)
^
第 2 步:" -42"(读入 '-' 字符,所以结果应该是负数)
^
第 3 步:" -42"(读入 "42")
^
解析得到整数 -42 。
由于 "-42" 在范围 [-231, 231 - 1] 内,最终结果为 -42 。
示例 3
输入:str = "4193 with words"
输出:4193
解释:
第 1 步:"4193 with words"(当前没有读入字符,因为没有前导空格)
^
第 2 步:"4193 with words"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
^
第 3 步:"4193 with words"(读入 "4193";由于下一个字符不是一个数字,所以读入停止)
^
解析得到整数 4193 。
由于 "4193" 在范围 [-231, 231 - 1] 内,最终结果为 4193 。
示例 4
输入:str = "words and 987"
输出:0
解释:
第 1 步:"words and 987"(当前没有读入字符,因为没有前导空格)
^
第 2 步:"words and 987"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
^
第 3 步:"words and 987"(由于当前字符 'w' 不是一个数字,所以读入停止)
^
解析得到整数 0 ,因为没有读入任何数字。
由于 0 在范围 [-231, 231 - 1] 内,最终结果为 0 。
示例 5
输入:str = "-91283472332"
输出:-2147483648
解释:
第 1 步:"-91283472332"(当前没有读入字符,因为没有前导空格)
^
第 2 步:"-91283472332"(读入 '-' 字符,所以结果应该是负数)
^
第 3 步:"-91283472332"(读入 "91283472332")
^
解析得到整数 -91283472332 。
由于 -91283472332 小于范围 [-231, 231 - 1] 的下界,最终结果被截断为 -231 = -2147483648 。
约束条件:
0 <= s.length <= 200
s
由英文字母(大写和小写)、数字(0-9
)、' '
、'+'
、'-'
和 '.'
组成class Atoi {
func myAtoi(_ str: String) -> Int {
var res = 0, flag = 1, index = 0
let intMax = 2147483647, intMin = -2147483648, strChars = Array(str)
// trim
while index < strChars.count {
let currentChar = strChars[index]
// trim
guard currentChar.isWhitespace else {
break
}
index += 1
}
guard index < strChars.count else {
return res
}
// handle flag
if strChars[index] == "-" {
flag = -1
index += 1
} else if strChars[index] == "+" {
index += 1
}
// cast to number
while index < strChars.count {
let currentChar = strChars[index]
guard currentChar.isNumber else {
break
}
res = res * 10 + currentChar.wholeNumberValue!
if res >= intMax {
if flag == 1 {
return intMax
} else if flag == -1 && res > intMax {
return intMin
}
}
index += 1
}
return flag * res
}
}
该算法题解的仓库:LeetCode-Swift[2]
点击前往 LeetCode[3] 练习
[1]
@故胤道长: https://m.weibo.cn/u/1827884772
[2]
LeetCode-Swift: https://github.com/soapyigu/LeetCode-Swift
[3]
LeetCode: https://leetcode.com/problems/string-to-integer-atoi/