LeetCode - Problems - Algorithms - 9. Palindrome Number
Problem Description
Given an integer x, return true if x 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 ๊ฐ์ ๋ฆฌํดํ๋ค.
//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์ ์ด์ฉํ ๊ฒ๋ณด๋ค ์กฐ๊ธ ๋ ํจ์จ์ ์์ ํ์ธํ ์ ์๋ค.
์ฝ๋๋ฅผ ์กฐ๊ธ ๋ ๊น๋ํ๊ฒ ๊ณ ์น๊ณ ์ถ์ง๋ง ์ค๋์ ๊ท์ฐฎ์์ ์ ๊น ํจ์ค...
'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 |