題目
原題頁面:https://leetcode.com/problems/reverse-integer/
題目型別:Math
難度評價:Easy
類似題目:(E) String to Integer (atoi)
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321Have 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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
分析
“反轉”一個數字。主要注意負數的處理。數值計算類面試題有一個經常會被忽略的重要點,就是數值溢位。這裡是用Python解題,所以對於超出int範圍的輸入引數處理還不會有問題。但是題目要求在int溢位的情況下返回0,因此要注意檢查輸入,並且在反轉的過程中時刻檢查是否溢位。
此外還要注意Python的一個坑,之前直接用的sys.maxint來表示int最大值,在64位win7上結果正確,但在leetcode網站上跑時就出錯了,發現是因為sys.maxint在windows上是32位,而在linux上則是64位,官方文件上說的也是 "This is at least 2**31-1"。
程式碼
1 | class Solution: |
