王廷瑋|數位醫療|智慧醫療: 7. Reverse Integer WFU

2024年7月2日 星期二

7. Reverse Integer

7. Reverse Integer


給定一個帶符號的32位整數 x,返回其數字反轉後的結果。如果反轉 x 會使值超出帶符號的32位整數範圍 [-2^31, 2^31 - 1],則返回 0。

假設環境不允許你存儲64位整數(帶符號或不帶符號)。


Python


class Solution:
def reverse(self, x: int) -> int:
# Initialize the result variable
result = 0
# Determine the sign of the input number
sign = 1 if x > 0 else -1
# Work with the absolute value of x
x = abs(x)
# Reverse the digits of the number
while x != 0:
# Get the last digit
last_digit = x % 10
# Append the last digit to the result
result = result * 10 + last_digit
# Remove the last digit from x
x = x // 10
# Restore the sign
result *= sign
# Check for overflow
if result < -2**31 or result > 2**31 - 1:
return 0
return result

16.52MB, 34ms


C++


class Solution {
public:
int reverse(int x) {
int result = 0;

while (x != 0) {
// Get the last digit
int last_digit = x % 10;
// Check for overflow before appending the last digit
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && last_digit > 7))
            return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && last_digit < -8))
            return 0;
// Append the last digit to the result
result = result * 10 + last_digit;
// Remove the last digit from x
x = x / 10;
}

return result;
}
};

7.56MB, 0ms


Javascript


/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
let result = 0;
const sign = Math.sign(x);
x = Math.abs(x);
while (x !== 0) {
const lastDigit = x % 10;
result = result * 10 + lastDigit;
x = Math.floor(x / 10);
}
result *= sign;
// Check for overflow
if (result < -(2 ** 31) || result > (2 ** 31) - 1) {
return 0;
}
return result;
};

52.77MB, 78ms