pub fn my_atoi(s: String) -> i32 {
let mut threshold_val: [u8; 10] = [50, 49, 52, 55, 52, 56, 51, 54, 52, 55];
let mut is_negative = false;
let mut has_digits = false;
let mut curr_idx: usize = 0;
let mut is_started = false;
let mut val: i32 = 0;
let s_bytes = s.as_bytes();
let mut is_overflow = false;
let mut is_overflow_ignored = false;
let mut is_full_match = true;
let mut val_vec: Vec<u8> = vec![];
loop {
if curr_idx == s_bytes.len() {
break;
}
if s_bytes[curr_idx] == 32 {
if !is_started {
curr_idx += 1;
continue;
} else {
break;
}
}
if [43u8, 45u8].contains(&s_bytes[curr_idx]) {
if has_digits {
break;
}
if !is_started {
if s_bytes[curr_idx] == 45 {
is_negative = true;
threshold_val = [50, 49, 52, 55, 52, 56, 51, 54, 52, 56];
}
is_started = true;
curr_idx += 1;
continue;
}
}
if 48 <= s_bytes[curr_idx] && s_bytes[curr_idx] <= 57 {
has_digits = true;
is_started = true;
if val == 0 && s_bytes[curr_idx] == 48 {
curr_idx += 1;
continue;
}
if val_vec.len() >= threshold_val.len() - 1 {
for idx in 0..val_vec.len() {
if !is_overflow {
if !is_overflow_ignored && val_vec[idx] > threshold_val[idx] {
is_overflow = true;
is_full_match = false;
break;
} else if val_vec[idx] < threshold_val[idx] {
is_full_match = false;
is_overflow_ignored = true;
}
}
}
if !is_overflow {
if val_vec.len() == threshold_val.len() - 1 {
if is_full_match
&& s_bytes[curr_idx] > threshold_val[threshold_val.len() - 1]
{
is_overflow = true;
break;
}
} else if val_vec.len() == threshold_val.len() {
is_overflow = true;
break;
}
}
}
if is_overflow {
break;
}
val = val * 10 + (s_bytes[curr_idx] - 48) as i32;
val_vec.push(s_bytes[curr_idx]);
curr_idx += 1;
continue;
}
break;
}
if is_overflow {
if is_negative {
-2147483648
} else {
2147483647
}
} else {
if is_negative {
-val
} else {
val
}
}
}