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).
中文翻譯
給予一個聲明為32位元的整數 x ,回傳翻轉數字的 x 。如果翻轉 x 導致其超過 32位元數字的上下限 [-231, 231 – 1] ,那就回傳 0
public class Solution {
public int Reverse(int x) {
bool neg = false; //是否為負數
if(x<0)
{
neg = true;
x = x*-1;
}
//轉為文字並翻轉
string y = x.ToString();
char[] arr = y.ToCharArray();
Array.Reverse(arr);
y = new string(arr);
int res = 0; //預設為 0
if(Int32.TryParse(y,out res)) //成功的話res會被新的值取代
{
res *= neg ? -1 : 1; //把負號補回來
}
return res;
}
}
因為超過Int32範圍的文字(數字),會無法轉換故會回傳false ➔ 最後就會回傳預設的 0
⭐方案2
public class Solution {
public int Reverse(int x) {
int res = 0;
while(x !=0)
{
int tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if(res%10!=tmp) //超過int的範圍
{
return 0;
}
}
return res;
}
}
Java解決方案
方案1
class Solution {
public int reverse(int x) {
boolean neg = false; //check if negative number
if(x<0)
{
neg = true;
x = x*-1;
}
//Convert to string than reverse by Array
String y = Integer.toString(x);
StringBuilder sb=new StringBuilder(y);
y = sb.reverse().toString();
try {
x = Integer.parseInt(y);
} catch (NumberFormatException e) {
return 0;
}
if(neg)
{
x*=-1;
}
return x;
}
}
運行時間 : 3ms
方案2
class Solution {
public int reverse(int x) {
int res = 0;
while(x !=0)
{
int tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if(res%10!=tmp) //exceed int range
{
return 0;
}
}
return res;
}
}
⭐運行時間 : 2ms
Python3 解決方案
方案1
class Solution:
def reverse(self, x: int) -> int:
x = str(x)
if x[0] == '-':
a = int('-' + x[-1:0:-1])
if a >= -2147483648 and a<= 2147483647:
return a
else:
return 0
else:
a = int(x[::-1])
if a >= -2147483648 and a<= 2147483647:
return a
else:
return 0
JavaScript 解決方案
方案1
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var res = 0;
while(x !=0)
{
var tmp = x%10;
res = res*10+tmp;
x = (x-tmp)/10;
if (res < -2147483648 || res > 2147483647)
{
return 0;
}
}
return res;
};
結論
這題其實挺有趣的,本來麻煩的判斷,善用Library 的TryParse就可以輕鬆解決
"the reverse side also has a reverse side"
Japanese proverb
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};