-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringToInteger.kt
More file actions
64 lines (53 loc) · 1.65 KB
/
StringToInteger.kt
File metadata and controls
64 lines (53 loc) · 1.65 KB
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
56
57
58
59
60
61
62
63
64
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/string-to-integer-atoi/)
*/
class StringToInteger {
enum class State {
START,
SIGN,
DIGIT,
END
}
private fun Char.isWhitespace() = (this == ' ')
private fun Char.isSign() = (this == '+' || this == '-')
private fun Char.digitToInt() = (this - '0')
fun myAtoi(s: String): Int {
var state = State.START
var sign = 1
var num = 0
var i = 0
loop@
while (i < s.length) {
when (state) {
State.START ->
when {
s[i].isWhitespace() -> i++
s[i].isSign() -> state = State.SIGN
s[i].isDigit() -> state = State.DIGIT
else -> state = State.END
}
State.SIGN -> {
if (s[i] == '-') sign = -1
state = State.DIGIT
i++
}
State.DIGIT ->
if (s[i].isDigit()) {
val d = s[i].digitToInt()
if (num > Int.MAX_VALUE / 10 || num == Int.MAX_VALUE / 10 && d > 7) {
return if (sign == -1) Int.MIN_VALUE else Int.MAX_VALUE
}
num = num * 10 + d
i++
} else {
state = State.END
}
State.END -> {
break@loop
}
}
}
return num * sign
}
}