LeetCode - palindrome number

katanazero·2020년 6월 8일
0

leetcode

목록 보기
12/13
post-thumbnail

palindrome number

  • Difficulty : easy

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

  • 회문 숫자인지 아닌지 검사하여 boolean 반환하기
  • Palindrome(회문)은 문자열을 거꾸로 해도 원래의 문자열과 같은 문자열인 특징을 가지고 있는 문자열을 가리키는 말 (예시 : 토마토, 양배추배양)

example
Example 1:
Input: 121
Output: true

Example 2:
Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

solution

  • 작성 언어 : javascript
  • Runtime : 236ms
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
        
    const reverseX = String(x).split('').reverse().join('');
    
    if(String(x) === reverseX) {
        return true;
    }
    
    return false;
    
};
  • 회문은 거꾸로 해도 문자가 같으면 되기때문에, 형변환을 하여 검사를 하였다.
  • 다른 방법은 문자에 시작인덱스와 끝인덱스를 하나씩 비교해보면 된다.
  • 실행시간은 이게 더 빠르다;
var isPalindrome = function(x) {
    
    const stringWrap = String(x);
    let startIndex = 0;
    let endIndex = stringWrap.length-1;
    
    while(startIndex < endIndex) {
    	if(stringWrap[startIndex] == stringWrap[endIndex]) {
      	startIndex++;
        endIndex--;
      } else {
      	return false;
      }
    
    }
    
    return true;
    
};
profile
developer life started : 2016.06.07 ~ 흔한 Front-end 개발자

0개의 댓글