【LeetCode】整数翻转

题目
在这里插入图片描述
     解决这个问题的三要素:

  1. 判断正负,将负数当做正数处理
int neg=x<0?-1:1;
//neg是一个状态标志位,将它与原数相乘一定得到正数
  1. 取出x值得个位,十位
个位:x%10
十位:x/10
  1. 判断溢出并返回0
if(n/10!=ret)
 return 0;
class Solution {
    public int reverse(int x) {
        if(x==Integer.MIN_VALUE)
        return 0;
        int neg=x<0?-1:1;
        x*=neg;
        int ret=0;
        while(x>0){
            int n=ret;
            n*=10;
            n+=x%10;
            x/=10;
            if(n/10!=ret) return 0;
            ret=n;
        }
        return ret*neg;
}}

猜你喜欢

转载自blog.csdn.net/weixin_43891901/article/details/106412461