LeetCode | Easy | Reverse Integer

Algorithm 2019. 8. 29. 15:42
반응형

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2:

Input: -123 Output: -321

Example 3:

Input: 120 Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

 

뒤집었는데 맨앞에 0이 있다면 0제거 

-부호가 있다면 뒤집고 앞에 - 부호 붙여주기 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
 
namespace Application
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var sol = new Solution();
            //9646324351, 1534236469
            //9646324351
            var result = sol.Reverse(12000);
            Console.WriteLine("result: {0}", result);
        }
    }
 
    public class Solution
    {
        public int Reverse(int x)
        {
            int answer = -1;
 
            bool isNagative = x <= 0 ? true : false;
 
            var stack = new Stack<int>();
            var str = x.ToString();
            int i = isNagative ? 1 : 0;
            for (; i < str.Length; i++) {
                stack.Push(int.Parse(str[i].ToString()));
            }
 
            int[] arr = new int[stack.Count];
            i = 0;
            while (stack.Count > 0) {
                arr[i++= stack.Pop();
            }
            
            i = 0;
            for (;  i < arr.Length; i ++) {
                if (arr[i] == 0) arr[i] = -1;
                else break;
            }
 
            var reversed = "";
            foreach (var n in arr) {
                if (n != -1) {
                    reversed += n.ToString();
                }
            }
 
            Console.WriteLine(reversed);
 
            answer = int.Parse(reversed);
 
            if (isNagative) answer = -1 * answer;
 
            return answer;
        }
    }
 
}
 
 
 

 

0이 들어올 경우 0 반환으로 해결 

근데 이건 뭐...정수 뒤집기 문제에서 갑자기 long?

반응형
: