7. 反轉整數

給定一個 32 位有符號整數,將整數中的數字進行反轉。spa

示例 1:code

輸入: 123
輸出: 321

 示例 2:blog

輸入: -123
輸出: -321

示例 3:io

輸入: 120
輸出: 21

注意:class

假設咱們的環境只能存儲 32 位有符號整數,其數值範圍是 [−231,  231 − 1]。根據這個假設,若是反轉後的整數溢出,則返回 0。di

 

 

 1 class Solution {
 2     public int reverse(int x) {
 3         int flag = x;
 4         if (x < 0)
 5             x = 0 - x;
 6 
 7         int res = 0;
 8         while (x != 0) {
 9             int pop = x % 10;
10 
11             // 防止溢出
12             if ((Integer.MAX_VALUE - pop) / 10.0 - res < 0) {
13                 return 0;
14             }
15             res = res * 10 + pop;
16             x = x / 10;
17         }
18 
19         if (flag < 0)
20             res = 0 -res;
21 
22         return res;
23         
24     }
25 }
相關文章
相關標籤/搜索