(C++練習) 7. Reverse Integer
題目 :
Given a 32-bit signed integer, reverse digits of an integer.
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.
大意 :
逆轉一個intege數字, 包含正負號, note 有提示要小心 超出邊界值。
1 class Solution { 2 public: 3 int reverse(int x) { 4 5 try 6 { 7 bool isNeg = x > 0 ? true : false; 8 int lastDigit; 9 int reverse = abs(x); 10 int res = 0; 11 while (reverse) 12 { 13 if (res > 214748364 || 14 res < -214748364 || 15 (res == 214748364 && x % 10 > 7) || 16 (res == -214748364 && x % 10 < -8)) 17 { 18 return 0; 19 } 20 lastDigit = reverse % 10; 21 res = res * 10 + lastDigit; 22 reverse = reverse / 10; 23 } 24 25 if (isNeg) 26 return res; 27 else 28 return res * -1; 29 } 30 catch (exception e) 31 { 32 return 0; 33 } 34 35 } 36 };优质内容筛选与推荐>>