干活干累了,刷一道题,一天保底两道,一年也就差很少刷完了 ----------7. Reverse Integer

这道题在17年的时候,我就刷过了,可是看到题目我也没有想起来我是怎么写的,而后看了一下提交记录,一会儿想起来了,而后就开始写,发现总体差很少,就有一点点的差异,之前多写了一个变量的,可是思路都是同样的。io

class Solution {
    public int reverse(int x) {
        //判断正负
        int negatives = 1;
        long res = 0;
        
        if(x < 0) negatives = -1;
        
        x = x * negatives;
        int tag = x; 
        
        while(x > 0){
            res = tag % 10 + res * 10;
            x = x / 10;
            tag = x;
        }
        
        if(res > Integer.MAX_VALUE) return 0;
        
        return (int) res * negatives;
    }
}class

总结:变量

1.主要在于tag变量与参数的取余。循环

2.对参数进行正负判断,并把正负保存到negatives变量中总结

3.而后对参数取正数,并付给中间变量tag,至关于计算使用tag,while的条件判断交给参数x,分工明确,而后对tag进行取余数,结果res*10+tag的余数while

 

--------------------------------改进的----------------------------------------return

是代码看着不那么多,循环中减小点代码参数

class Solution {
    public int reverse(int x) {
        int negatives = 1;
        if(x < 0) negatives = -1;
        x = x * negatives;//取正
        long res = 0;//结果
        while(x > 0){
            res = x % 10 + res * 10;
            x /= 10; 
        }
        
        if(res > Integer.MAX_VALUE) return 0;
        
        return (int) res * negatives;
        
    }
}tag

相关文章
相关标签/搜索