[Leetcode] 7. Reverse Integer
[Leetcode] 7. Reverse Integer

[Leetcode] 7. Reverse Integer

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 08์›” 02์ผ
floatFirstTOC: right

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

์ž…๋ ฅ๋ฐ›์€ ์ˆซ์ž๋ฅผ ๊ฑฐ๊พธ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ๋งจ ๋’ค ์ˆซ์ž๊ฐ€ 0์ด๋ผ๋ฉด ์ด๋Š” ์ƒ๋žตํ•œ๋‹ค.
ย 
ํŒŒ์ด์ฌ์—์„œ๋Š” ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์–ด์ฐจํ”ผ ๋ฒ”์œ„๋„ int ํ˜•์œผ๋กœ ์ฃผ์–ด์กŒ๊ธฐ ๋•Œ๋ฌธ์—, ๊ทธ๋ƒฅ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•œ ํ›„ str ๋กœ ๋ณ€ํ™˜ํ•œ ๋ฌธ์ž์—ด์„ ๋’ค์ง‘์€ ํ›„ ๋‹ค์‹œ int ํ˜•์œผ๋กœ ๋ฐ”๊พธ๋ฉด ๋œ๋‹ค.
ย 
C++์€ ์ˆ˜ํ•™์ ์œผ๋กœ ์ ‘๊ทผํ•˜๋ฉด ๋œ๋‹ค. x๊ฐ€ ๋‚จ์ง€ ์•Š์„ ๋•Œ๊นŒ์ง€ 10์œผ๋กœ ๋‚˜๋ˆ ์„œ, ๊ทธ ๋‚˜๋จธ์ง€๋ฅผ ๊ณฑํ•ด์ฃผ๋ฉด ๋œ๋‹ค.
ย 

โš™๏ธย Python

class Solution: def reverse(self, x: int) -> int: # ์˜ค๋ฅ˜ ๋ฒ”์œ„ ์ •์˜ INT_MAX = 2**31 - 1 INT_MIN = -(2**31) # ์Œ์ˆ˜์ธ์ง€ ํ™•์ธ sign = -1 if x < 0 else 1 x = abs(x) # ์ˆซ์ž ๋’ค์ง‘๊ณ  ๋ถ€ํ˜ธ ์ ์šฉ reversed_number = int(str(x)[::-1]) * sign # ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ๊ฒ€์‚ฌ if reversed_number < INT_MIN or reversed_number > INT_MAX: return 0 return reversed_number if __name__ == "__main__": sol = Solution() print(sol.reverse(123)) # 321
ย 

โš™๏ธย C++

class Solution { public: int reverse(int x) { int result = 0; while (x != 0) { int pop = x % 10; x /= 10; // ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ฒดํฌ if (result > INT_MAX / 10 || (result == INT_MAX / 10 && pop > 7)) return 0; if (result < INT_MIN / 10 || (result == INT_MIN / 10 && pop < -8)) return 0; result = result * 10 + pop; } return result; } };
  • 321๊ฐ€ ๋“ค์–ด๊ฐ”์„ ๋•Œ:
    • pop ์— 10์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ์‚ฝ์ž…, ์ฒ˜์Œ ์‹œํ€€์Šค์—์„œ 1
    • ์ดํ›„ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ๋ฅผ ์ฒดํฌํ•œ ํ›„, result ์— 10์„ ๊ณฑํ•œ ํ›„ pop ์„ ๋”ํ•จ
      • ์ฒซ ์‹œํ€€์Šค์—์„œ๋Š” 0 * 10 + 1 = 1
    • x ๊ฐ€ 0์ด ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
      • ๋‘ ๋ฒˆ์งธ ์‹œํ€€์Šค๋ถ€ํ„ฐ 1 * 10 + 2 = 12 , 12 * 10 + 3 = 123 ์‹์œผ๋กœ ์ด์–ด๋‚˜๊ฐ
ย 

๐Ÿ“Œย ์†Œ๊ฐ

๋Œ“๊ธ€

guest