Reverse digits of an integer. Example1: x = 123, return 321 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. Update (2014-11-10): Subscribe to see which companies asked this question 題目明確提示了你要考慮反轉(zhuǎn)后溢出的的問題。如果溢出了,返回什么都不合適,那就統(tǒng)一返回一個(gè)錯(cuò)誤代碼吧,return 0吧 在C#中,用int.MaxValue表示最大數(shù)。用int.MinValue表示最小數(shù)。 123/10=12;非個(gè)位 123%10=3;個(gè)位 提交的方法應(yīng)該判斷下是否輸入的是負(fù)數(shù),但是,我添加負(fù)數(shù)的處理邏輯,就報(bào)錯(cuò)了。 我在實(shí)際的VS13的C#項(xiàng)目中測(cè)試了一下,發(fā)現(xiàn)沒有錯(cuò)。就算輸入為負(fù)數(shù),下面的代碼輸出依然正確。 是我想錯(cuò)了。錯(cuò)的原因是我數(shù)序的錯(cuò)誤。-45%10 =-5;我想當(dāng)然的認(rèn)為只有正數(shù)才能取余數(shù)。 public class Solution { public int Reverse(int x) { long sum=0; while(x!=0) { int s=x%10;//取得個(gè)位數(shù) sum=sum*10+s;// x=x/10; } if(sum>int.MaxValue||sum<int.MinValue) { return 0; } return (int)sum; } } |
|