7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123Output: 321
Example 2:
Input: -123Output: -321
Example 3:
Input: 120Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.class Solution {public: int reverse(int x) { int flag = 1; if(x < 0) flag = -1, x *= -1; long long sum = 0; while(x){ sum = (sum * 10 + (x % 10)); x /= 10; } long long ans = sum * flag; return (ans > INT_MAX || ans < INT_MIN)? 0 : ans; }};