[Algorithm] Leetcode_ Reverse Integer

JAsmine_log·2024년 4월 14일

Reverse Integer

Problem

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 [-231, 231 - 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

Solution & Analysis

Tip
integer 숫자의 범위를 초과하면 답을 찾을 수 없다.
-2^31 <= integer <= 2^31 - 1

Code

Code1

x의 값을 10(Divisor)로 계속 나누어, 나머지에 10을 곱해 쌓는 형태로 알고리즘 만들기

//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/

class Solution {
   
    private static final int DIVISOR = 10;

	public int reverse(int x) {
    	
        if (x < 10 && x > -10) return x;
        
        long result = 0; //else if case 이후에 변수 선언, testcase가 부족한 건 아닐까?		
        int remainder=0;
        while (x != 0) {
            remainder = x % DIVISOR;
            result = result * DIVISOR + remainder;
            x /= DIVISOR;
        }
        if (result > 2147483647 || result < -2147483648) return 0;

        return (int)result;
    }
}

Code2

x를 byte type의 배열로 만들어, left/right 포인트로 reverse하여 마지막값 체크

//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/

class Solution {
   TBD
}

Tip
Integer.MAX_VALUE
Integer.MIN_VALUE

profile
Everyday Research & Development

0개의 댓글