๋ชฉ์ฐจ
LeetCode - Problems - Algorithms - 7.Reverse Integer
Problem Description
Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
- Input: x = 123
- Output: 321
Example 2:
- Input: x = -123
- Output: -321
Example 3:
- Input: x = 120
- Output: 21
Example 4:
- Input: x = 0
- Output: 0
Constraints:
- -231 <= x <= 231 - 1
My Solution (C#)
public class Solution {
public int Reverse(int x) {
string num;
string reversed;
if (x < 0)
{
num = Convert.ToString(x * (-1));
reversed = "-";
}
else
{
num = Convert.ToString(x);
reversed = "";
}
for (int i = num.Length - 1; i >= 0; i--)
{
reversed += num.Substring(i, 1);
}
try
{
return Convert.ToInt32(reversed);
}
catch
{
return 0;
}
}
}
์ฒซ๋ฒ์งธ if ๋ฌธ: ์ฃผ์ด์ง int๊ฐ์ string ๊ฐ์ผ๋ก ๋ณํํ๋ค.
(์์์ผ ๊ฒฝ์ฐ -๋ฅผ reversed์ ์ถ๊ฐํ๊ณ , ์ฃผ์ด์ง ์ซ์์ -1์ ๊ณฑํ ๋ค ๋ณํํ๋ค.)
for ๋ฐ๋ณต๋ฌธ: ๋ณํ๋ string ๊ฐ์ ์ ์ผ ๋ท ๊ฐ์ reversed์ ์ถ๊ฐํ๋ค.
๊ทธ๋ ๊ฒ ๋ค์ง์ ๊ฐ์ int ๊ฐ์ผ๋ก ์ฌ๋ณํํ์ฌ ๋ฆฌํดํ๋ค.
์ด๋ int์ ๋ฒ์๋ฅผ ์ด๊ณผํ ๊ฒฝ์ฐ 0์ ๋ฆฌํดํ๋ผ๊ณ ํ์ผ๋ try catch๋ฌธ์ ์ด์ฉํด ์๋ฌ๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ 0์ returnํ๋๋ก ์์ธ์ฒ๋ฆฌ๋ฅผ ํด์ผํ๋ค.

์๋๋ ์์ธ์ฒ๋ฆฌ๋ฅผ ๋ฐฐ์ฐ์ง ๋ชปํ 1๋ 1๊ฐ์ ์ ์ ๋ด๊ฐ ์์ฑํ๋ ์ฝ๋.
public class Solution {
public int Reverse(int x) {
long result = 0;
while (x != 0)
{
result = result * 10 + x % 10;
x /= 10;
}
return (int)result == result ? (int)result : 0;
}
}
int ๊ฐ์ ๋ฒ์ด๋๋ ๊ฒ์ ์ด๋ป๊ฒ ํด๊ฒฐํด์ผํ ์ง ๋ชฐ๋ผ์ ๊ทธ๋ฅ long ๋ณ์๋ฅผ ๋ง๋ค์ด์ ํด๊ฒฐํ๋ค.
๊ทธ๋ ์ง๋ง ์ฃผ์ด์ง ์กฐ๊ฑด์ ์ถฉ์กฑํ์ง ๋ชปํ๋ฏ๋ก ์ ๋ต์ด ๋ ์ ์๋ค. (Leetcode์์๋ ์ ๋ต์ฒ๋ฆฌ๋ฅผ ํ๋ค.)

'Problem solving > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [LeetCode] 13. Roman to Integer (C#) (0) | 2021.01.24 |
|---|---|
| [LeetCode] 9. Palindrome Number (C#) (0) | 2021.01.23 |
| [LeetCode] 1. Two Sum (C#) (0) | 2021.01.21 |
| [LeetCode] 1646. Get Maximum in Generated Array (Python) (0) | 2021.01.16 |
| [LeetCode]Daily Challenge: Boats to Save People (Python) (0) | 2021.01.13 |