Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
此题注意边界条件 -2^31 < int < 2 ^ 31 - 1 在C++里,9 * 1000,000,000 = 410065408, 不等于9,000,000,000. 但是 2 * 1,000,000,000 = 2,000,000,000.
1 class Solution { 2 public: 3 int reverse(int x) { 4 if(x == 0) return 0; 5 6 bool positive = true; 7 if(x < 0){ 8 positive = false; 9 x = -x; 10 } 11 vector<int> v; 12 while(x){ 13 v.push_back(x % 10); 14 x /= 10; 15 } 16 int n = v.size(); 17 long long temp = 0; 18 for(int i = 0; i < n; i++) 19 temp += v[n - 1 - i] * (pow(10, i)); 20 if(temp > INT_MAX || (!positive && temp < INT_MIN)) return 0; 21 else 22 return positive ? temp : -temp; 23 } 24 };
1 class Solution { 2 public: 3 int reverse(int x) { 4 if(x == -2147483648) return 0; 5 string s; 6 int positive = 1; 7 if(x < 0) {x = -x; positive = -1;} 8 while(x){ 9 char temp = x % 10 + '0'; 10 s += temp; 11 x /= 10; 12 } 13 int result = string2int(s); 14 if(result){ 15 if(positive == -1) return -result; 16 return result; 17 } 18 return 0; 19 } 20 21 int string2int(string s){ 22 if(s.length() > 10 || (s.length() == 10 && s[0] > '2')) return 0; 23 double result = 0; 24 int exponential = 1; 25 for(int i = s.length() - 1; i >= 0; i--){ 26 int temp = s[i] - '0'; 27 result += temp * exponential; 28 exponential *= 10; 29 } 30 if(result > 2147483647.0) return 0; 31 return result; 32 } 33 };
class Solution { public: int reverse(int x) { if(x == 0) return 0; bool positive = true; if(x < 0){ positive = false; x = -x; } vector<int> v; while(x){ v.push_back(x % 10); x /= 10; } int n = v.size(); long long temp = 0; for(int i = 0; i < n; i++) temp += v[n - 1 - i] * (pow(10, i)); if(temp > INT_MAX || (!positive && temp < INT_MIN)) return 0; else return positive ? temp : -temp; } };