push
github
847 of 908 branches covered (93.28%)
Branch coverage included in aggregate %.
58 of 66 new or added lines in 2 files covered. (87.88%)
3117 of 3197 relevant lines covered (97.5%)
5.1 hits per line
| 1 |
// 8. 字符串转换整数 (atoi):https://leetcode.cn/problems/string-to-integer-atoi/
|
|
| 2 |
// 输入:" -042"
|
|
| 3 |
// 输出:-42
|
|
| 4 |
|
|
|
|
export function stringToIntegerAtoi (s: string): number { |
|
|
|
let res = 0
|
7✔ |
|
|
let sign = 1
|
7✔ |
|
|
let i = 0
|
7✔ |
|
|
const len = s.length
|
7✔ |
|
|
while (i < len && s[i] === ' ') { |
|
|
|
i++ |
1✔ |
|
|
} |
1✔ |
|
|
if (i < len && s[i] === '-') { |
|
|
|
sign = -1
|
2✔ |
|
|
i++ |
2✔ |
|
|
} |
2✔ |
|
|
if (i < len && s[i] === '+') { |
|
|
|
if (sign === -1) return 0 |
|
|
|
i++ |
1✔ |
|
|
} |
|
|
|
while (i < len && s[i] >= '0' && s[i] <= '9') { |
|
|
|
res = res * 10 + Number(s[i])
|
12✔ |
|
|
i++ |
12✔ |
|
|
} |
|
|
|
res = res * sign |
6✔ |
|
|
const intMax = 2 ** 31 - 1 |
6✔ |
|
|
if (res > intMax) {
|
|
|
NEW
|
return intMax
|
× |
|
NEW
|
} |
|
|
|
const intMin = -(2 ** 31) |
6✔ |
|
|
if (res < intMin) {
|
|
|
NEW
|
return intMin
|
× |
|
NEW
|
} |
|
|
|
return res
|
6✔ |
|
|
} |
6✔ |