Post

๐Ÿ’ก 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.