21 lines
684 B
Rust
21 lines
684 B
Rust
fn main() {
|
|
println!("{}", my_atoi(String::from("2147483648")));
|
|
}
|
|
|
|
pub fn my_atoi(s: String) -> i32 {
|
|
let s = s.trim();
|
|
let is_neg = s.starts_with('-');
|
|
let skip_sign = if is_neg || s.starts_with('+') { 1 } else { 0 };
|
|
let mut result = 0i32;
|
|
for byte in s.bytes().skip(skip_sign) {
|
|
if byte < b'0' || byte > b'9' { break; }
|
|
let digit = (byte - b'0') as i32;
|
|
if let Some(checked_result) = result.checked_mul(10).and_then(|n| n.checked_add(digit)) {
|
|
result = checked_result;
|
|
} else {
|
|
return if is_neg { i32::MIN } else { i32::MAX };
|
|
}
|
|
}
|
|
if is_neg { result = -result; }
|
|
return result;
|
|
}
|