일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 연결리스트 정렬
- 문자열제곱
- 임의 정밀도 / 큰 수 연산
- 문자열
- LeetCode 83번
- 시뮬레이션
- 큐
- 재귀
- 별 찍기
- 이분 탐색
- LeetCode Remove Duplicates from Sorted List in c
- 큰 수 연산
- 프로그래머스
- 연결리스트 중복제거
- 사칙연산
- 브루트포스 알고리즘
- 유클리드 호제법
- 실패함수
- 해시를 사용한 집합과 맵
- 스택
- 자료 구조
- 정렬
- 다이나믹 프로그래밍
- Queue
- KMP알고리즘
- 정수론
- LeetCode 83 c언어
- 조합론
- 구현
- 수학
- Today
- Total
hahn
[LeetCode - C] 9. Palindrome Number 본문
Palindrome Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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 a palindrome while 123 is not.
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
Follow up: Could you solve it without converting the integer to a string?
Solution 1
숫자를 각 자릿수 별로 쪼개 배열로 저장한 뒤, 비교하는 방법
Follow up 때문에 itoa 사용 안 했으나 사실 다를 게 없는 것 같다.
bool isPalindrome(int x)
{
int *num_arr;
int size;
int num;
int idx;
size = 0;
idx = 0;
num = x;
if (x < 0)
return (false);
while (num)
{
num /= 10;
size++;
}
if (!x)
return (true);
num_arr = (int *)malloc(sizeof(int) * size);
while (x)
{
num_arr[idx++] = x % 10;
x /= 10;
}
idx = 0;
while (idx < --size)
{
if(num_arr[idx++] != num_arr[size])
return (false);
}
free(num_arr);
return (true);
}
Solution 2
(leetcode 제공)
revertedNumber에 x의 1번째 자릿수부터 순서대로 넣는 방법
주의해야할 점은 자릿 수가 짝수냐 홀수에 따라 조건 판단이 조금 달라진다
예외처리 부분은 010과 같이 맨 앞 자릿수가 0인 경우는 존재할 수 없으니
x < 0과 같이 false 처리해줬음.
bool isPalindrome(int x)
{
if(x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while(x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber/10;
}
}
총평
처음에는 숫자를 리버스 하려 했으나 귀찮아서 itoa 사용하여 해결하려했다.
하지만 follow up을 보고 Solution 1과 같이 처리했다.
결론적으로 itoa를 이용해 해결하는 것과 동일한 방법이었다.
leetcode에서 제공한 코드는 내가 리버스 하려 했던 것보다
좀 더 나아간 방법으로 확실히 좋은 방법이다.
'코딩테스트 연습 > LeetCode(C - Easy)' 카테고리의 다른 글
[LeetCode - C] 26. Remove Duplicates from Sorted Array (0) | 2022.03.25 |
---|---|
[LeetCode - C] 21. Merge Two Sorted Lists (0) | 2022.03.24 |
[LeetCode - C] 20. Valid Parentheses (0) | 2022.03.23 |
[LeetCode - C] 14. Longest Common Prefix (0) | 2022.03.23 |
[LeetCode - C] 13. Roman to Integer (0) | 2022.03.22 |