Leetcode题解之字符串(2)颠倒整数

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/33/

题目描述:

 颠倒整数

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31,  2^31 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。

思路:第一种思路。利用和反转字符串的思路。先将所有字符串反转,然后判断是否以0为结尾。把0消除就好。其次就是反转后末尾带 ‘-’ 的问题。这里我只想到用另一个大小为原数组小1的char 数组,去复制。刚好最后一位为'-'号被抛去。返回-b就可以获得正解。至于反转后溢出我没考虑。。。

 第二种思路。利用入栈出栈的思考方法。

参考leetcode解法:

方法:弹出和推入数字 & 溢出前进行检查

思路

我们可以一次构建反转整数的一位数字。在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。

算法

反转整数的方法可以与反转字符串进行类比。

我们想重复“弹出” xx 的最后一位数字,并将它“推入”到 \text{rev}rev 的后面。最后,\text{rev}rev 将与 xx 相反。

要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。

//pop operation:
pop = x % 10;
x /= 10;

//push operation:
temp = rev * 10 + pop;
rev = temp;

但是,这种方法很危险,因为当 temp = rev * 10 + pop;时会导致溢出。

幸运的是,事先检查这个语句是否会导致溢出很容易。

为了便于解释,我们假设 rev 是正数。

11

当 rev 为负时可以应用类似的逻辑。

呃。。我还能说什么....这两个方法,一个天,一个是地啊。

//解法1
class Solution {
    public int reverse(int x) {
        String str = String.valueOf(x);
        int len = str.length();
        char[] ch = new char[len];
        int b=0 ;
        for(int i=0;i<ch.length;i++){
            ch[i] = str.charAt(len-1-i);
           
        }
        for(int j=len-1;j>1;j--){
              if(ch[j-1]==0){
                ch[j-1]=' ';
                   System.out.print(ch[j]);
            }
          
        }
        if(ch[len-1]=='-'){
                char[] ch2 =new char[len-1];
                for(int k =0;k<ch2.length;k++){
                    ch2[k]=ch[k];
                    System.out.println(ch2[k]);
                }
                String str2 = String.valueOf(ch2);
                try {
                b = Integer.valueOf(str2).intValue();
                } catch (NumberFormatException e) {
                e.printStackTrace();
                }
                return -b;
       }
        String str2 = String.valueOf(ch);
        try {
        b = Integer.valueOf(str2).intValue();
        } catch (NumberFormatException e) {
        e.printStackTrace();
        }
        return b;
    }
}

//解法2:
class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84027559