Reverse digits of an integer.

Example1:x = 123, return 321
Example2:x = -123, return -321

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function shouldreturn 0 when the reversed integer overflows.

分析

这道题主要是要小心越界,所以初始化result的时候,一定要设置为long, 而不是int

public class Solution {
    public int reverse(int x) {

          long result = 0;
          while(x != 0){
              result = 10*result + x % 10;
          }
        if(result < Integer.MIN_VALUE || result > Integer.MAX_VALUE){
            return 0;
        }
        return  (int)result;
    }
}

results matching ""

    No results matching ""