[LeetCode-Easy]007. 顛倒整數(shù)

題目:

給定一個(gè)范圍為 32 位 int 的整數(shù),將其顛倒。
例 1:
輸入: 123
輸出: 321
例 2:
輸入: -123
輸出: -321
例 3:
輸入: 120
輸出: 21

思路:

用StringBuffer也很基礎(chǔ)了,但是有個(gè)問(wèn)題是int太大了容易溢出。問(wèn)題里說(shuō)溢出則一律取0,那就很簡(jiǎn)單了。寫(xiě)個(gè)異常捕獲,出NumberFormatException異常固定輸出0。

代碼:

public class Solution007 {

public static int reverse(int x) {
    int result;
    StringBuffer sb = new StringBuffer();
    sb.append(x);
    sb.reverse();
    try {
        if (x>=0){
                result = Integer.valueOf(sb.toString());
        }else {
            result = Integer.parseInt(sb.substring(0,sb.length()-1).toString());
            result = 0 - result;
        }
    }catch (NumberFormatException e){
        result = 0;
    }
    return result;
}


public static void main(String[] args) {
    System.out.println(reverse(1534236469));

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容