日常刷题——整数反转

日常刷题——整数反转

给出一个32位有符号的整数,将整数中每位上的数字进行反转。
(PS:假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。)

原思路:

 public static int lengthOfLongestSubstring(String s) {
  String temp = "";

        List<Integer> len = new ArrayList<Integer>();
        int result = 0;
        int origin = 0;
        if (!s.isEmpty() && !s.equals("")) {
            temp = String.valueOf(s.charAt(0));
        }
        for (int i = 1; i < s.length(); i++) {
            if (temp.contains(String.valueOf(s.charAt(i)))) {
                temp = String.valueOf(s.charAt(i));
                len.add(i - origin+1);
                origin = i;
            
            } else {
                temp = temp + String.valueOf(s.charAt(i));
            }
  }
        if (len.isEmpty()) {
            len.add(s.length());
        }

        if (!temp.isEmpty()) {
            result = Collections.max(len);
        } else {
            result = 0;

        }
        return result;
 }

优化:

public int reverse(int x) {
           long y = 0;
        while (x != 0) {
            y = y * 10 + x % 10;
            x = x / 10;
        }
        if(y>Integer.MAX_VALUE||y<Integer.MIN_VALUE){
            return 0;
        }
        return (int)y;
    }

Integer.MAX_VALUE: int 类整数的最大值(2的31次方-1=2147483647)

题目来自LeetCode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值