728x90
https://leetcode.com/problems/string-to-integer-atoi/description/
public class Solution
{
public int MyAtoi(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
int start = 0;
while ((start < s.Length) && (s[start] == ' '))
{
++start;
}
if (start == s.Length)
return 0;
int sign = 1;
char first = s[start];
if (first == '+')
{
++start;
}
else if (first == '-')
{
sign = -1;
++start;
}
int end = start;
while ((end < s.Length) && (char.IsDigit(s[end])))
{
++end;
}
end -= 1;
if (start > end)
return 0;
bool res = int.TryParse(s.Substring(start, end - start + 1), out int result);
if (res == false)
{
return sign == 1 ? int.MaxValue : int.MinValue;
}
return (result * sign);
}
}
728x90
'Programing > Algorithm' 카테고리의 다른 글
[LeetCode] 15. 3Sum (0) | 2025.02.10 |
---|---|
[LeetCode] 11. Container With Most Water (0) | 2025.02.08 |
[LeetCode] 7. Reverse Integer (0) | 2025.02.07 |
[LeetCode] 6. Zigzag Conversion (0) | 2025.02.07 |
[LeetCode] 5. Longest Palindromic Substring (0) | 2025.02.07 |