LeetCode 7. Reverse Integer 一個整數倒敘輸出
潛在問題:(1)隨著求和可能精度會溢出int 范圍,需要使用long 來輔助判斷是否溢出,此時返回 0
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.
(2)去前綴0
eg: reverse(1534236469); 會丟精度,如果不校驗 所以WA了一次
int reverse(int x) { long sumLong = 0; int sum = 0; int num = 0; while (x!= 0) { //支持正負數 num = x % 10; //末尾數字 sum = sum * 10;//進位 sum += num; x = x / 10; //校驗精度 sumLong = sumLong * 10; sumLong += num; if (sumLong != sum) { sum = 0; break; } } return sum; }
posted on 2018-09-08 23:50 ACM_Someone like you 閱讀(179) 評論(0) 收藏 舉報
浙公網安備 33010602011771號