Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
這個題比較簡單,考慮特殊情況如12000,注意檢查反轉後數字是否會越界溢出。代碼如下:
class Solution { public: int reverse(int x) { bool minus = false; short int splitNum[10]; int i = 0, j = 0; unsigned int num, result = 0; unsigned int MAX = 2147483647; unsigned int MIN = 2147483648; if(x < 0) { num = 0 - x; minus = true; } else { num = x; } while(num != 0) { splitNum[i++] = num%10; num = num/10; } while(splitNum[j] == 0) j++; while(j < i) { if(!minus && (MAX-splitNum[j])/10 >= result) { result = result*10 + splitNum[j]; j++; } else if(minus && (MIN-splitNum[j])/10 >= result) { result = result*10 + splitNum[j]; j++; } else { return 0; } } return minus ? (0-result) : result; } };