LeetCode 7. Reverse Integer 一个整数倒叙输出

潜在问题:(1)随着求和可能精度会溢出int 范围,须要使用long 来辅助判断是否溢出,此时返回 0this

               Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.spa

               (2)去前缀0code

eg: reverse(1534236469); 会丢精度,若是不校验 因此WA了一次blog

 

int reverse(int x) {
    long sumLong = 0;
    int sum = 0;
    int num =  0;
    while (x!= 0) {    //支持正负数
        num = x % 10;  //末尾数字
        sum = sum * 10;//进位
        sum += num;
        x = x / 10;
        //校验精度
        sumLong = sumLong * 10;
        sumLong += num;
        if (sumLong != sum) {
            sum = 0;
            break;
        }
    }
    return sum;
}
相关文章
相关标签/搜索