LeetCode 7. Reverse Integer整数逆記述出力

1929 ワード

潜在問題:(1)和可能精度がint範囲をオーバーフローするにつれてlongを用いてオーバーフローの有無を判断するのを補助する必要があり,このとき0を返す
               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.
(2)接頭辞0
eg: reverse(1534236469); 精度を落としてしまうので、チェックしないとWAが1回
 
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;
}

 
転載先:https://www.cnblogs.com/someonelikeyou/p/9611139.html