log 2022-02-19
blog
gitlive라는 확장이 있는데, 기능이 어떠한지 궁금하다. 동시편집이 아니라, 비디오 등 소셜 기능에 대한 것으로 보이긴 한다.
sport
leetcode 문제풀이 - string to integer
https://leetcode.com/problems/string-to-integer-atoi/
.1
의 경우 0이어야 하는데 1로 처리해서 틀림. (leading space만 무시하고, 그 뒤론 바로 숫자라고 생각하되, ‘.’이 나왔으므로 바로 0이 되는게 맞는 모양이다.)- 위의 경우 처리하려고 고치다가 두 번 더틀림.
pub fn my_atoi(s: String) -> i32 {
// 1. lead space remove
let chs = s.chars();
let mut iter = chs.into_iter();
let mut sign: i64 = 1;
let mut in_num = false;
let mut value: i64 = 0;
let mut num_len = 0;
let mut ans: i32 = 0;
let mut clamp = false;
for (idx, ch) in iter.enumerate() {
if (in_num) {
if (!"0123456789".contains(ch)) {
// end of number part. ignore rest
in_num = false;
break;
} else {
// add the number and multiply 10
num_len += 1;
if value > (i32::MAX) as i64 {
value = i64::MAX;
break;
}
value *= 10;
value += ch.to_digit(10).unwrap() as i64;
}
}
// 1. ignore spaces
if (!in_num && ch != ' ') {
in_num = true;
// sign = if ch == '-' { -1 } else { 1 };
// ignore leading zeros
// what if 0~9?
if ch == '-' {
sign = -1;
} else if ch == '+' {
sign = 1;
} else if ("123456789".contains(ch)) {
value += ch.to_digit(10).unwrap() as i64;
num_len += 1;
} else if ('0' != ch) {
dbg!("asdasd");
return 0;
}
}
}
let mut ans = 0;
// dbg!((value, sign));
if (value > i32::MAX as i64) {
ans = if (sign > 0) { i32::MAX } else { i32::MIN };
} else {
ans = (value * sign) as i32;
}
// dbg!(ans);
ans
}
Comments