Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solution: first count the number of digits, then reverse it. Overflow is not considered.
Following code passes LeetCode Online Large Judge.
class Solution { public: int reverse(int x) { int result = 0, tmp = abs(x); bool sign = (x > 0); while(tmp > 0) { result *= 10; result += tmp % 10; tmp /= 10; } if(!sign) result = -1*result; return result; } };
Comments
Post a Comment