๐ก LeetCode 9 - Palindrome Number
๐ก LeetCode 9 - Palindrome Number
๋ฌธ์
Given an integerย x, returnย trueย ifย xย is a palindrome, and false otherwise.
์ ์ถ๋ ฅ ์์
โ ์์ 1
1
2
3
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
โ ์์ 2
1
2
3
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.
โ ์์ 3
1
2
3
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
์ ์ฝ์กฐ๊ฑด
-231 <= x <= 231 - 1
์์ฑ ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isPalindrome(int x) {
// 1. ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํ
int remainder;
int originX = x;
int reversedX = 0;
// 2. ํฐ๋ฆฐ๋๋กฌ ์ ํ๋ณ
while (x > 0) {
reversedX *= 10;
remainder = x % 10;
reversedX += remainder;
x /= 10;
}
// 3. ๋ฐํ
return originX == reversedX ? true : false;
}
}
ํ๊ณ
- ํฐ๋ฆฐ๋๋กฌ ์๋ฅผ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ ํฌ๊ฒย ๋ฌธ์์ด ์ฐ์ฐ๊ณผ ์ซ์ ์ฐ์ฐ ๋ ๊ฐ์ง ๋ฐฉ๋ฒ์ด ์๋๋ฐ, ๋ฌธ์์ด ์ฐ์ฐ์ ์๋๋ ๋๋ฆฌ๊ณ , ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ง์ด ์ก์๋จน๋๋ค.
- ์ฆ ๋ฌธ์์ด ์ฐ์ฐ์ด ์๋ ์ซ์ํ ๋ณ์๋ฅผ ํตํด ๋๋จธ์ง ์ฐ์ฐ์ ํ๋ ๋ฐฉ๋ฒ์ด ๊ฐ์ฅ ํจ์จ์ ์ด๋ค.
This post is licensed under CC BY 4.0 by the author.
