[LeetCode] Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
每次取出个位,然后放到新的数里。
1 class Solution { 2 public: 3 int reverse(int x) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int sign = x > 0 ? 1 : -1; 7 x = abs(x); 8 9 int ret = 0; 10 while(x) 11 { 12 int digit = x % 10; 13 ret = ret * 10 + digit; 14 x /= 10; 15 } 16 17 return ret * sign; 18 } 19 };