floatFirstTOC: right
๐ฅ๏ธย ์์ํ๋ฉฐ
๋ฌธ์๋ฅผ ์ซ์๋ก ๋ณํํ๋ ํจ์๋ฅผ ์์ฑํ๋ ๊ฒ์ด ๋ชฉํ๋ค. ์กฐ๊ฑด์ ์๋์ ๊ฐ๋ค.
- ๊ณต๋ฐฑ์ ๋ฌด์ํ๋ค.
- ๋งจ ์ ๋ถํธ๋ฅผ ์ ์ธํ ๋ฌธ์๋ฅผ ๋ฌด์ํ๋ค.
- ๋งจ ์ ๋ฌธ์๊ฐ ๋ถํธ๊ฐ ์๋ ๋ฌธ์๋ผ๋ฉด ์ ์ฒด๋ฅผ ๋ฌด์ํ๋ค.
int
ํ์ ๋ฒ์๋ฅผ ๋๋๋ค๋ฉด ํด๋น ๋ถ๋ถ์ ์ต๋๊ฐ์ ๋ฆฌํดํ๋ค.
ย
โ๏ธย Python
1๏ธโฃย ๊ฐ์ ์ ๋ฒ์
class Solution: def myAtoi(self, s: str) -> int: s = s.strip() # ๊ณต๋ฐฑ ์ ๊ฑฐ sign = 1 # ๋ถํธ res = 0 # ๊ฒฐ๊ณผ๊ฐ if s == "" or s[0].isalpha(): # ๋ฌธ์์ด์ด ๋น์ด์๊ฑฐ๋ ๋ฌธ์๋ก ์์ํ๋ ๊ฒฝ์ฐ return 0 if s[0] == "+" or s[0] == "-": # ๋ถํธ๊ฐ ์๋ ๊ฒฝ์ฐ sign = -1 if s[0] == "-" else 1 s = s[1:] for i in s: if not i.isdigit(): break res = res * 10 + int(i) return min(res, 2**31 - 1) if sign == 1 else max(-res, -(2**31)) if __name__ == "__main__": sol = Solution() print(sol.myAtoi("-42"))
ย
2๏ธโฃย ๊ฐ์ ํ ๋ฒ์
class Solution: def myAtoi(self, s: str) -> int: s = s.strip() # ๊ณต๋ฐฑ ์ ๊ฑฐ if not s: return 0 sign = 1 res = 0 int_max, int_min = 2**31 - 1, -(2**31) if s[0] in "+-": sign = -1 if s[0] == "-" else 1 s = s[1:] for char in s: if not char.isdigit(): break res = res * 10 + int(char) # ์ฑ๋ฅ ํฅ์์ ์ํด ๋ฒ์๋ฅผ ๋์์ ๊ฒฝ์ฐ ์ฆ์ ๋ฆฌํด if sign == 1 and res > int_max: return int_max if sign == -1 and res * sign < int_min: return int_min return max(int_min, min(sign * res, int_max)) if __name__ == "__main__": sol = Solution() print(sol.myAtoi("-42"))
โ๏ธย C++
#include <cctype> // for std::isdigit #include <iostream> #include <limits> // for std::numeric_limits #include <string> class Solution { public: int myAtoi(const std::string &str) { int i = 0, sign = 1; long result = 0; // long์ ์ฌ์ฉํ์ฌ ์ค๋ฒํ๋ก์ฐ ๋ฐฉ์ง // 1. ๊ณต๋ฐฑ ์คํต while (i < str.size() && std::isspace(str[i])) { i++; } // 2. ๋ถํธ ์กด์ฌํ๋ฉด ์ฒ๋ฆฌ if (i < str.size() && (str[i] == '+' || str[i] == '-')) { sign = (str[i] == '-') ? -1 : 1; i++; } // 3. ์ซ์๋ก ๋ณํ while (i < str.size() && std::isdigit(str[i])) { int digit = str[i] - '0'; // 4. ์ค๋ฒํ๋ก์ฐ, ์ธ๋ํ๋ก์ฐ ์ฒ๋ฆฌ if (result > (std::numeric_limits<int>::max() - digit) / 10) { return (sign == 1) ? std::numeric_limits<int>::max() : std::numeric_limits<int>::min(); } result = result * 10 + digit; i++; } return static_cast<int>(result * sign); } }; int main() { Solution sol; std::cout << sol.myAtoi("-42") << std::endl; // -42 return 0; }
ย
๋๊ธ