[Leetcode] 8. String to Integer (atoi)
[Leetcode] 8. String to Integer (atoi)

[Leetcode] 8. String to Integer (atoi)

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 08์›” 08์ผ
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; }
ย 

๐Ÿ“Œย ์†Œ๊ฐ

๋Œ“๊ธ€

guest