Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. 一開始題目有點沒看懂。不知道為什么會溢出。其實是因為,給你的是十進制,而二進制有符號32位能表示的位數是有限的。所以反轉后還是可能溢出的。
int reverse(int x) { long res = 0; while(x) { res = res*10 + x%10; x /= 10; } return (res<INT_MIN || res>INT_MAX) ? 0 : res;}一開始的答案如上所示,INT_MIN和INT_MAX(頭文件:limits.h)分別是-2147483648(-2^31)和2147483647(2^31-1),是int能表示的最小的和最大的數。這個答案被accept了,但是只beat了5%左右的人。后來看到了某大神的答案。int reverse(int x) {int ans = 0;while (x) { int temp = ans * 10 + x % 10; if (temp / 10 != ans) //如果不等的話說明temp已經溢出了 return 0; ans = temp; x /= 10;}return ans;}這個能自動檢測是否溢出,而不是靠與INT_MAX和INT_MIN比較來檢測溢出,這個比較過程非常耗時。
新聞熱點
疑難解答