LeetCode整数反转(Reverse digits of an integer)解法

整数反转

题目

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123

输出: 321

示例 2:

输入: -123

输出: -321

示例 3:

输入: 120

输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
分析:

  • 方法一:

  • 我们使用比较麻烦的一种解法,这种解法会使用很多Java的函数,我将会在注释里给出方法


```java
public int reverse(int x) {
    
        String s = Integer.toString(x);
        StringBuilder sb = new StringBuilder();
    
       	//charAt(int index) 返回指定索引处的 char 值。
        if(s.charAt(0) == '-')
            //substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。
            //append(String str) 将指定的字符串追加到此字符序列。
            sb.append(s.substring(1))
        else
            sb.append(s);
    	//reverse() 将此字符序列用其反转形式取代。
        sb.reverse();
    
        if(s.charAt(0) == '-')
            //insert(int offset, char c) 将 char 参数的字符串表示形式插入此序列中
            sb.insert(0,'-');
    
        Long res = Long.parseLong(sb.toString());
        if(res<Integer.MIN_VALUE || res>Integer.MIN_VALUE)
            return 0;
        //转换成int返回
        return res.intValue();
}

方法二:


```java
public int reverse(int x) {
    
     long temp = 0;
    
     while(x != 0){
    	 temp = temp*10 + x%10;
         x = x/10;
      }
    
     if(temp>Integer.MAX_VALUE || temp<Integer.MIN_VALUE)
     	 return 0;
     return (int) temp;
}
  • 这个解法咋一看上去,哇!这么简单。仔细看就会发现有点耍流氓,我们用到了Long类型。而题目说只能存下int,这似乎有点不合规矩。那么怎么样才能在不使用long类型的情况下结局对int类型溢出的判断呢。

  • 思路:我们首先要明确int溢出后的变化,我们给出一段代码来了解一下

    public static void main(String[] args) {
            int imax=Integer.MAX_VALUE;
            int imin=Integer.MIN_VALUE;
    
            int a=imax+1;
            int b=imin-1;
            System.out.println("int类型Max "+imax+" int类型Min"+imin);
            System.out.println("向上溢出"+a);
            System.out.println("向下溢出"+b);
        }
    
    //out
    /**
    int类型Max:2147483647  int类型Min-2147483648
    向上溢出-2147483648
    向下溢出2147483647
    */

我们不难发现,int溢出后所发生的变化,那么我们就可以根据这个特性去改良我们的代码,让他更合规矩一些

public int reverse(int x) {

        int reversed_x = 0;
        
        while (x != 0) {
            int temp = reversed_x * 10 + x % 10;
            x = x / 10;
            //增加了这么一个小细节,如果temp发生溢出数值就会改变,那么就会返回0
            if (temp / 10 != reversed_x) {
                reversed_x = 0;
                break;
            }
            reversed_x = temp;
        }
        return reversed_x;
    
}
发布了12 篇原创文章 · 获赞 0 · 访问量 97

猜你喜欢

转载自blog.csdn.net/adressdeep/article/details/104909782