本文共 1622 字,大约阅读时间需要 5 分钟。
public class Solution { private static final int maxDiv10 = Integer.MAX_VALUE / 10; private static final int minDiv10 = Integer.MIN_VALUE / 10; public int reverse(int x) { int num = 0; while(x != 0){ int tmp = x % 10; if ( num > maxDiv10 || num < minDiv10){ return 0; } num = num*10 + tmp; x /= 10; } return num; }}
To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?
class Solution {public: int reverse(int x) { bool minus = (x < 0 ? true : false); x = abs(x); int ret = 0; int base = 0; while (x != 0){ base = x % 10; x = x / 10; if (multiplication_is_safe(ret, 10)){ ret *= 10; }else{ return 0; } if (addition_is_safe(ret, base)){ ret += base; }else{ return 0; } } return minus ? -ret : ret; } bool multiplication_is_safe(int32_t a, int32_t b){ int32_t p = a * b; return !a || p/a == b; } bool addition_is_safe(int32_t a, int32_t b){ return (a + b >= 0); }};
转载地址:http://ijpbb.baihongyu.com/