일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 | 31 |
Tags
- 제로베이스 프론트엔드 스쿨
- 알고리즘
- JavaScript
- 카드뉴스
- html&css
- react-query
- leetcode
- wai-aria
- 정규표현식
- react
- 프로그래머스
- TypeScript
- 디자인
- 웹접근성
- 비트연산자
- programmers
Archives
- Today
- Total
記錄
[JS] 7. Reverse Integer 본문
문제 링크: https://leetcode.com/problems/reverse-integer/
난이도: Medium
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2³¹, 2³¹ - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
32비트 정수 x가 주어지면 숫자를 반대로 하여 x를 반환합니다. 만약 반전된 x의 값이 32비트 정수 범위 [-2³¹, 2³¹ - 1]를 벗어나면 0을 반환합니다.
환경에서 64비트 정수(signed 또는 unsigned)를 저장할 수 없다고 가정합니다.
환경에서 64비트 정수(signed 또는 unsigned)를 저장할 수 없다고 가정합니다.
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints 제약 조건:
- -2³¹ <= x <= 2³¹ - 1
문제 풀이
revNum(reversed Number)
: x를 string으로 변환 > array로 변환하고 reverse()로 순서를 반대로 변경 > join() 으로 string으로 변경 > parseInt로 Number 타입으로 변경한다.
이 경우 음수가 양수로 나오기 때문에 Math.sign() 메소드를 활용해 x가 음수일 때 결과값을 처리한다.
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let revNum=parseInt([...String(x)].reverse().join(''));
if (revNum>Math.pow(2,31)-1) return 0;
return Math.sign(x)*revNum;
};
사용한 Method 정리 (MDN 문서 링크)
- parseInt() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt
- Math.sign() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
- Math.pow() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/pow
- Array.reverse() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
- Array.join() : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Array.prototype.join() - JavaScript | MDN
join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
developer.mozilla.org
'FRONTEND STUDY > LeetCode' 카테고리의 다른 글
[JS] 34. Find First and Last Position of Element in Sorted Array (1) | 2022.10.14 |
---|---|
[JS] 136. Single Number (0) | 2022.10.12 |
[JS] 215. Kth Largest Element in an Array (0) | 2022.10.11 |
[JS] 50. Pow(x, n) (0) | 2022.10.08 |
[JS] 01. Two Sum (0) | 2022.10.07 |
Comments