Problem solving/Algorithms

[LeetCode] 9. Palindrome Number (C#)

Young_A 2021. 1. 23. 11:22

LeetCode - Problems - Algorithms - 9. Palindrome Number

Problem Description

Given an integer x, return true if is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.

 

Example 1:

  • Input: x = 121
  • Output: true

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.

Example 4:

  • Input: x = -101
  • Output: false

Constraints:

  • -231 <= x <= 231 - 1

My Solution (C#)

//Converting to string 
public class Solution {
    public bool IsPalindrome(int x) {
        string str = Convert.ToString(x);

        int frontIndex = 0;
        int backIndex = str.Length - 1;


        while (true)
        {
            if (frontIndex >= backIndex)
            {
                return true;
            }
            else if(str[frontIndex] == str[backIndex])
            {
                frontIndex++;
                backIndex--;
                continue;
            }
            else
            {
                return false;
            }
        }
    }
}

์œ„ ๋ฌธ์ œ๋Š” ๊ฐ„๋‹จํ•˜๊ฒŒ int ๊ฐ’์„ string์œผ๋กœ ๋ณ€๊ฒฝ, ์ดํ›„ string index ๊ฐ’์„ ์ฐจ๋ก€๋กœ ํ™•์ธํ•˜๊ณ , ์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ’์ด ํ™•์ธ ๋  ๊ฒฝ์šฐ false ๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.

Result: LeetCode - 9. Palindrome Number - Used string Conversion.

//Checking integer by calculation
public class Solution {
    public bool IsPalindrome(int x) {
        int reverseX = 0;
        int tempX = x;
        while(tempX != 0)
        {
            reverseX = reverseX*10 + tempX%10;
            tempX /= 10;
        }
        if ((x==reverseX && x > 0)||x==0)
        {
            return true;
        }
        
        return false;
    }
}

์œ„ ํ•ด๊ฒฐ๋ฒ•์€ 1๋…„ ์ „์— C#์„ ๋ฐฐ์šฐ๊ณ  ์–ผ๋งˆ ์•ˆ๋˜์—ˆ์„๋•Œ ํ’€์—ˆ๋˜ ๋ฐฉ๋ฒ•

runtime์„ ๋น„๊ตํ•ด๋ณด๋ฉด ์ˆซ์ž๋ฅผ ์ด์šฉํ•œ ํ’€์ด ๋ฐฉ๋ฒ•์ด runtime๋„, memory usage๋„ string conversion์„ ์ด์šฉํ•œ ๊ฒƒ๋ณด๋‹ค ์กฐ๊ธˆ ๋” ํšจ์œจ์ ์ž„์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

์ฝ”๋“œ๋ฅผ ์กฐ๊ธˆ ๋” ๊น”๋”ํ•˜๊ฒŒ ๊ณ ์น˜๊ณ  ์‹ถ์ง€๋งŒ ์˜ค๋Š˜์€ ๊ท€์ฐฎ์•„์„œ ์ž ๊น ํŒจ์Šค...

Result: LeetCode - 9. Palindrome Number - Calculating the given number

'Problem solving > Algorithms' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] 14. Longest Common Prefix (C#)  (0) 2021.01.25
[LeetCode] 13. Roman to Integer (C#)  (0) 2021.01.24
[LeetCode] 7. Reverse Integer (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