[LeetCode] 5.Palindrome Number
2020. 12. 29. 15:36
leetcode.com/problems/palindrome-number/
1. Problem
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Follow up: Could you solve it without converting the integer to a string?
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
2. Code
package leetCode;
public class PalindromeNumber {
public static void main(String[] args) {
int x = 90009;
if(isPalindrome(x) == true) {
System.out.println("true");
} else {
System.out.println("false");
}
}
public static boolean isPalindrome(int x) {
if(x < 0) {
return false;
}
//배열에 숫자를 넣는다.
int []arr = new int[sizeNum(x)];
for(int i = 0; i < arr.length; i++) {
int sn = sizeNum(x);
if(sn != arr.length-i) {
arr[i] = 0;
} else {
int rn = realNum(x);
arr[i] = rn;
x = x - zegop(rn, sn);
}
}
//반복문을 돌려서 왼쪽과 오른쪽을 비교 점점 가운데로 들어온다.
for(int i = 0; i < arr.length; i++) {
int end = arr.length-i-1;
if(i >= end) {
break;
}
if(arr[i] != arr[end] ) {
return false;
}
}
return true;
}
public static int sizeNum(int n) {
int size = 0;
while(n >= 1) {
n = n/10;
size++;
}
return size;
}
public static int realNum(int x) {
if(x == 0) {
return 0;
}
while(x >= 10) {
x = x/10;
}
return x;
}
public static int zegop(int x, int size) {
for(int i = 0 ; i < size-1; i++) {
x = x*10;
}
return x;
}
}
3. Report
String을 쓰면 간단히 풀 수 있는 문젠데 조건에 String을 쓰지 말라 되어 있어서너무 복잡하게 만든 것 같다. 오류투성...
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 7.Longest Common Prefix (0) | 2020.12.30 |
---|---|
[LeetCode] 6.Merge Two SortedLists (0) | 2020.12.30 |
[LeetCode] 4.Reverse Integer (0) | 2020.12.28 |
[LeetCode] 3.Roman to Integer (0) | 2020.12.28 |
[LeetCode] 2.Add Two Numbers (0) | 2020.12.28 |