【LeetCode】7. Reverse Integer 整型数反转

题目: 

  Reverse digits of an integer.

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

思路:不断取最低位加到先前值得后面,如下:

        while(x!=0){
          res=res*10+x%10;
          x/=10;
        }

   还要注意反转后可能会出现溢出的情况。

public class Solution {
    public int reverse(int x) {
        long res=0;
        while(x!=0){
            res=res*10+x%10;
            x/=10;
        }
        
        if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){
            return 0;
        }else{
            return (int)res;
        }
    }
}

  

原文地址:https://www.cnblogs.com/zhstudy/p/5999369.html