[Palindrome Number]05-14

Algorithmus 2019. 5. 14. 17:20




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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Algorithm2
{
    public class App
    {
        public void Start()
        {
            int a;
            bool b;
 
            a = 121;
            b = this.IsPalindrome(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = -121;
            b = this.IsPalindrome(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = 122222222;
            b = this.IsPalindrome(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = -143289579;
            b = this.IsPalindrome(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            Console.WriteLine("======================");
 
            a = 121;
            b = this.IsPalindrome2(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = -121;
            b = this.IsPalindrome2(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = 122222222;
            b = this.IsPalindrome2(a);
            Console.WriteLine("{0} : {1}", a, b);
 
            a = -122125135;
            b = this.IsPalindrome2(a);
            Console.WriteLine("{0} : {1}", a, b);
 
        }
 
        //
        public bool IsPalindrome(int x)
        {
            if (x < 0)
            {
                x *= -1;
            }
 
            var charX = x.ToString();
 
            return charX[0== charX[charX.Length - 1];
        }
        
        //문자열로 바꾸지 않고 하기
        public bool IsPalindrome2(int x)
        {
            if (x < 0)
            {
                x *= -1;
            }
 
            int i = 1;
            int firstNum = 0;
 
            //첫번째 자리 구하기
            while (true)
            {
                var a = x / i;
 
                if (a == 0)
                {
                    break;
                }
                i *= 10;
                firstNum = a;
            }
 
            var lastNum = x % 10;
 
            return firstNum == lastNum;
        }
    }
}
 
cs


'Algorithmus' 카테고리의 다른 글

AStar algorithm 4방향(캐릭터 이동)  (0) 2019.05.21
AStar algorithm  (0) 2019.05.20
[TwoSum]05-04  (0) 2019.05.04
[TwoSum]05-03  (0) 2019.05.03
<선택정렬 알고리즘>수정1  (0) 2019.03.29
: