Given an integer x
, return true
if x
is a palindrome__, and false
otherwise.
x = 121
true
121 reads as 121 from left to right and from right to left.
x = -121
false
From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
x = 121
true
Reads 01 from right to left. Therefore it is not a palindrome.
Could you solve it without converting the integer to a string?
"토마토" 나 "기러기" 처럼 거꾸로 읽어도 똑같은 단어를 Palindrome(팔린드롬) 이라고 부른다.
입력으로 들어온 정수 x
가 거꾸로 읽어도 똑같은 정수라면 true
를 아니면 false
를 반환하는 문제이다.
x
가 음수이면 절대 Palindrome(팔린드롬)이 될 수 없다.
문자열로 변환해 접근하면 조금 더 쉽겠지만, Follow-up
에 나와있듯 문자열로 변환하지 않고 접근해보려한다.
위 순서를 수행할 때, x의 복사복을 저장한 변수를 이용해 핸들링해야한다.
why? 마지막에 반전된 x 가 들어있는 변수와 x 를 비교해야하기 때문에....
x 가 다 소진될 때 까지 반복을 하면 아래와 같은 이미지가 될 것이다.
위 반복을 수행 후 temp 가 x와 같으면 true 를, 같지 않으면 false 를 반환하면 될 것 같다.
public static boolean solution(int x) {
if (x가 음수이면?)
return false;
int reverse = 뒤에서부터 뒤집어 저장하기 위한 변수
int temp = 기존 x 는 보존하면서 복사본을 핸들링하기 위한 변수
while (temp 가 0 이 될 때까지) {
int lastNum = 마지막 수 추출 후 변수 저장
reverse = 역순으로 저장
temp = 추출한 수 제외한 x
}
return 역순으로 저장된 reverse 와 x 비교 후 같으면 true 같지 않으면 false 반환
}
public static boolean solution(int x) {
if (x < 0)
return false;
int reverse = 0;
int temp = x;
while (temp != 0) {
int lastsNum = temp % 10;
reverse = reverse * 10 + lastsNum;
temp = temp / 10;
}
return (reverse == x);
}
위 문제에서는 문자열로 변환하지 않고 접근했다면, 문자열로 변환해서 접근하는 방법을 알아보자
public static boolean solution(int x) {
if (x가 음수이면?)
return false;
String strX = x를 문자열로 변환한다.
String reverse = 문자열로 변환 된 x 를 뒤집는다.
return strX 와 reverse 를 비교한다.
}
public static boolean solution(int x) {
if (x < 0)
return false;
String strX = Integer.toString(x);
String reverse = new StringBuilder(strX).reverse().toString();
return strX.equals(reverse);
}