본문 바로가기
LeetCode

[LeetCode] 7. Reverse Integer

by JungSeung 2023. 10. 16.
728x90

https://leetcode.com/

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^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

 

Example 2:

Input: x = -123
Output: -321

 

Example 3:

Input: x = 120
Output: 21

 

Constraints:
-2^31 <= x <= 2^31 - 1

 

Code :

// 정수를 뒤집어 반환하는 함수
var reverse = function(x) {
    // 입력 값이 0인 경우, 0을 반환
    if (x === 0) return 0;
    // 입력 값이 양수인 경우
    if (x > 0) {
        // 숫자를 문자열로 변환하고 뒤집은 후 다시 정수로 변환
        let result = parseInt(x.toString().split('').reverse().join(''));
        // 결과가 32비트 정수 범위를 벗어나면 0을 반환
        return result < Math.pow(2, 31) - 1 ? result : 0;
    } else { // 입력 값이 음수인 경우
        // 숫자를 문자열로 변환하고 각 자릿수를 배열로 분리
        let result = x.toString().split('');
        // 부호를 배열 끝에 추가하고 배열 첫 번째 요소 제거 (부호 위치 조정)
        result.push('-');
        result.shift();
        // 배열을 뒤집고 다시 정수로 변환
        result = result.reverse();
        result = parseInt(result.join(''));
        // 결과가 32비트 정수 범위를 벗어나면 0을 반환
        return result > Math.pow(-2, 31) ? result : 0;
    }
};

 

Solutions Code :

// 정수 뒤집기 함수
var reverse = function(x) {
  // 결과를 저장할 변수 초기화
  let rev = 0;
  // 입력 값의 부호 저장
  const sign = x < 0 ? -1 : 1;
  // 입력 값의 절대값으로 계산 진행
  x = Math.abs(x);
  // 입력 값이 0이 될 때까지 반복
  while (x !== 0) {
    // 현재 자릿수 구하기
    const digit = x % 10;
    // 결과에 현재 자릿수를 추가하여 뒤집기
    rev = rev * 10 + digit;
    // 다음 자릿수를 처리하기 위해 입력 값 업데이트
    x = Math.floor(x / 10);
  }
  // 부호를 곱하여 최종 결과 얻기
  const result = sign * rev;
  // 결과가 32비트 정수 범위를 벗어나면 0 반환
  if (result > 2 ** 31 - 1 || result < -(2 ** 31)) return 0;
  // 최종 결과 반환
  return result;
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90