難度為簡單
Runtime: 2 ms, faster than 95.12% of Java online submissions for Reverse Integer.
Memory Usage: 33.9 MB, less than 100.00% of Java online submissions for Reverse Integer.
以上是我用的時間跟記憶體
以上是我用的時間跟記憶體
題目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
這題要處理益位的問題,try catch要會用,最基本最基本也要會(Exception這個) 才可以成功解決這題
package leetCode;
public class ReverseInteger {
public static void main(String[] args) {
// TODO Auto-generated method stub
newnewSolution so = new newnewSolution();
System.out.println(so.reverse(77777));
}
}
class newnewSolution {
int tryParseInt(String value) {
try {
return Integer.parseInt(value); //字串轉陣列的方法
} catch (NumberFormatException nfe) { //也可以用Exception 最大父類別直接代替
//益位回傳0
return 0;
}
}
public int reverse(int x) {
String intNum = String.valueOf(x); //或x.toString(); 這樣寫也可以
String strAns = new String();
char[] temp = intNum.toCharArray(); //把字串轉乘我們要的字元陣列
boolean negativeNum = false; //存是不是負數
if (temp[0] == '-') {
negativeNum = true; //如果有負號先加負號
strAns += '-';
}
for (int i = temp.length - 1; i >= 0; i--) { //從陣列反者加回去
if (temp[i] == '-') {
continue; //如果有負號但上面加過了,就略過
} else {
strAns += temp[i];
}
}
int intAns = tryParseInt(strAns);
return intAns;
}
};
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記