PROGRAMING/C#

[Algorithm] Palindrome Number

donghunl 2024. 4. 27. 10:08
반응형

Palindrome : 회문(回文) 또는 팰린드롬(palindrome)은 거꾸로 읽어도 제대로 읽는 것과 같은 문장이나 낱말, 숫자, 문자열(sequence of characters) 등입니다.

 

Question:Given an integer x, return true if x is a palindrome, and false otherwise.

Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

 

Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

 

Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:
-231 <= x <= 231 - 1

 

주어진 문제는 입력받은 정수가 거꾸로 읽어도 바로 읽은 것과 똑같은 숫자가 되는지를 확인하는 문제입니다.

 

Solution:우선 주어진 문제를 풀기 위해 입력받은 정수를 문자열 변수로 바꿔준 후 반복문을 통해 첫번째 문자와 마지막 문자, 앞에서 두번째 문자와 뒤에서 두번째 문자 이런식으로 비교해 가면서 주어진 숫자의 중간값까지 비교하면서 모든 문자가 같아지면 참(true), 반복문 중에 하나라도 다르면 거짓(false) 리턴해주면 됩니다.

public class Solution {
    public bool IsPalindrome(int x) {
        string k = x.ToString(); // convert to string from integer 문자열로 변환        
        
        for(int i=0;i<k.Length/2;i++) // 해당 문자를 중간까지만 처리하도록 함   
        {
            if(k[i] != k[k.Length-1-i]) // compare charactor between first++ and last-- 순차적으로 문자를 비교
            {
                return false;           // if any char not the same, return false 값이 같지 않다면 거짓을 리턴
            }
        }
        return true;
    }
}

First, to solve the given problem, convert the input integer into a string variable.

Compare the first and last characters, the first and second characters, and the second characters....until the repeat statement is executed to the middle value.

If all characters are the same, return true.

If any of the repetitions are different, return false.

반응형

'PROGRAMING > C#' 카테고리의 다른 글

[Algorithm] Reverse each word  (5) 2024.05.02
[Algorithm] Valid Palindrome  (67) 2024.04.30
[Algorithm] Integer to Roman  (100) 2024.04.25
[Algorithm] Median of Two Sorted Arrays  (132) 2024.04.22
[Algorithm] Add Two Numbers  (84) 2024.04.21