1. 问题描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution.
class Solution { public: int reverse(int x){ } };
2. 解答思路
2.1. 为什么会有溢出?
整数的存储方式:最高位为符号位
- 16位整数范围:-2^15~2^15-1,即-32768到32767
- 32位整数范围:-2^31~2^31-1,即-2147483648到2147483647
2.2. 如何判断溢出?
- 传入的整数x的范围是:-2147483648 到 2147483648,反转后(暂不考虑溢出问题):-2147483648 --> -8463847412; 2147483647 -->7463847412。
- 由32位整数的范围知,当且仅当整数x是10位数时,才可能溢出。
- 当x是10位数时,考虑个位,若x%10 > 2,则溢出;若x%10 < 2,则未溢出;若x%10 == 2,则需考虑x的十位。若十位为1,则需考虑百位,以此类推..
3. 代码
1 class Solution { 2 public: 3 int reverse(int x){ 4 bool bIsPositive = x > 0; 5 x = bIsPositive ? x : -x;//也可调用求绝对值的函数abs(x) 6 7 if (IsOverFlow(x))//处理溢出 8 { 9 return 0; 10 } 11 12 int result = 0; 13 while (0 != x) 14 { 15 result = result *10 + x%10; 16 x = x/10; 17 } 18 if (!bIsPositive) 19 { 20 result = -result; 21 } 22 23 return result; 24 } 25 private: 26 /*! fn bool IsOverFlow(int x) 27 * rief 判断输入的整数x是否溢出. 28 * param[in] x 用户输入的32位整数. 29 * eturn 结果. 30 * - true 溢出. 31 * - false 未溢出. 32 */ 33 bool IsOverFlow(int x) 34 { 35 if (-2147483648 == x)//注意,-2147483648的绝对值溢出,-x仍未-2147483648,故需单独判断。 36 { 37 return true; 38 } 39 40 int nBitCount = 0;//记录当前输入整数的位数 41 int tx = x; 42 while (0 != tx) 43 { 44 nBitCount++; 45 tx = tx/10; 46 } 47 if (10 == nBitCount)//2147483647 1463847412 48 { 49 if (recIsOverFlow(x)) 50 { 51 return true; 52 } 53 } 54 55 return false; 56 } 57 /*! fn bool recIsOverFlow(int x, int idx = 1463847412) 58 * rief 递归判断输入的整数x是否溢出. 59 * param[in] x 用户输入的32位整数. 60 * param[in] idx 用于判断溢出的整数. 61 * eturn 结果. 62 * - true 溢出. 63 * - false 未溢出. 64 */ 65 bool recIsOverFlow(int x, int idx = 1463847412) 66 { 67 int x_remainder = x % 10; 68 int idx_remainder = idx % 10; 69 70 if (x_remainder > idx_remainder) 71 { 72 return true; 73 } 74 else if (x_remainder == idx_remainder && x!=0 && idx!=0) 75 { 76 return recIsOverFlow(x/10, idx/10); 77 } 78 return false; 79 } 80 };
4. 反思
对于-2147483648,由于其绝对值溢出,-x仍未-2147483648,故需单独判断。