-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy path8.string-to-integer-atoi.kt
55 lines (47 loc) · 1.39 KB
/
8.string-to-integer-atoi.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode id=8 lang=kotlin
*
* [8] String to Integer (atoi)
*/
class Solution {
fun myAtoi(str: String): Int {
var ans = arrayListOf<Int>()
var first = false
var flag = 1
var pos = 0
for (i in 0 until str.length) {
if (str[i] != ' ') {
if (str[i] in '0' .. '9' || str[i] == '-' || str[i] == '+') {
if (str[i] == '-') flag = -1
first = true
pos = i
}
break
}
}
if (!first) {
return 0
} else {
pos = if (str[pos] == '-' || str[pos] == '+') pos+1 else pos
while (pos < str.length && str[pos] == '0') pos++
while (pos < str.length && str[pos] in '0'..'9') {
ans.add(str[pos]-'0')
pos++
}
var cnt: Long = 1
var res: Long = 0
if (ans.size > 10) {
return if (flag == -1) -2147483648 else 2147483647
}
for (i in ans.size-1 downTo 0) {
res += ans[i]*cnt
cnt *= 10
if (res >= Int.MAX_VALUE) break
}
res *= flag
if (res < Int.MIN_VALUE) res = -2147483648
if (res > Int.MAX_VALUE) res = 2147483647
return res.toInt()
}
}
}