1. 程式人生 > >LeetCode刷題-007反轉整數

LeetCode刷題-007反轉整數

reverse const 數字 rev 輸出 span 溢出 範圍 一個

給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1:
輸入 : 123
輸出 : 321
示例 2:
輸入 : ‐123
輸出 : ‐321
示例 3:
輸入 : 120
輸出 : 21
註意 :
假設我們的環境只能存儲 32 位有符號整數,其數值範圍是 [?2 31 , 2 31 ? 1]。根據這個假設,如果反轉後的整數溢出,則返回 0。

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4     const int int_max=0x7fffffff;
 5     const int int_min=0x80000000;
 6     long
long anwser=0; 7 while(x!=0) 8 { 9 anwser=anwser*10+(x%10); 10 x/=10; 11 } 12 if(anwser<int_min || anwser>int_max) 13 { 14 anwser=0; 15 } 16 return anwser; 17 } 18 };

LeetCode刷題-007反轉整數