7、整数反转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/G_drive/article/details/89743241

问题描述

在这里插入图片描述

问题分析

分析题目,此题考的是简单的数值处理,只用判断范围+取除取余即可。正好我对于Java的BigInterger不太熟悉,通过这个题目加深理解。也有其他方法,比如数字转为字符串之后在调用字符串反转方法,或者使用堆栈之类的,并没有太多技巧性的地方,就不过多赘述了。

  • 时间复杂度:O( log(n) ),x 中有 log10(x)位数字 。
  • 空间复杂度:O( 1 )

Java代码

import java.math.BigInteger;

class Solution {
    public int reverse(int x) {
        BigInteger result = BigInteger.valueOf(0);

        while (x != 0){
            result = result.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(x%10));
            x = x/10;
        }

        if ( (result.compareTo(BigInteger.valueOf(2147483647)) == 1) || (result.compareTo(BigInteger.valueOf(-2147483647)) == -1)){
            return 0;
        }



        return result.intValue();
    
        
    }
}

结果分析

以上代码的执行结果:

执行时间 内存消耗
12ms 35MB

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/G_drive/article/details/89743241