LeetCode 7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 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.
1,烂解
int reverse(int x) { int sign = 1; if(x == 0x80000000) { return 0; } if(x < 0) { x = x * (-1); sign = -1; } double num = 0; while(1) { if(num * 10 > 2147483647) { return 0; } if((x - x % 10) == 0) { num = num * 10 + x % 10; break; }else { num = num * 10 + x % 10; x = x / 10; } } if(sign < 0) { num = num * (-1); } return num; }
浙公网安备 33010602011771号