码迷,mamicode.com
首页 > 编程语言 > 详细

算法之整数反转

时间:2019-11-30 21:16:09      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:cat   value   博客   new   toc   能力   class   逻辑   long   

题目

给出一个 32 位的有符号整数,将这个整数中每位上的数字进行反转。注意不要超出整数数值范围
-- 来自 Leetcode Easy

解决方式

public class Solution {

    public int reverse(int x) {
        // 方式一:将int整数转化为字符串,再转化为char[]数组进行倒叙遍历
        // 执行用时3ms 内存消耗34MB
        char[] chars = Integer.toString(x).toCharArray();
        int before = 0;
        // 如果是负数的话,before向后移一位,从1开始
        if (chars[0] == '-') {
            before = 1;
        }
        char save;
        for (int end = chars.length - 1; before < end; before++, end--) {
            save = chars[before];
            chars[before] = chars[end];
            chars[end] = save;
        }

        // 防止超出int范围的报错
        int reverse = 0;
        try {
            reverse = Integer.parseInt(String.valueOf(chars));
        } catch (Exception e) {

        }
        return reverse;
    }

    public int reverse2(int x) {
        // 方式二:将int整数对10进行取模取余
        // 执行用时1ms 内存消耗33.5MB
        int term;
        long b = 0;
        while (x != 0) {
            // 余数
            term = x % 10;
            // 向前一位
            x = x / 10;
            // 造逆序新数字
            b = b * 10 + term;
        }
        if (b > Integer.MAX_VALUE || b < Integer.MIN_VALUE) {
            return 0;
        }
        return (int) b;
    }
}
public class Test {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int reverse = solution.reverse2(-3215686);
        System.out.println(reverse);
    }
}

怎么说呢,训练一下自己的逻辑能力,以后再厉害一点,回过头来看看有什么可以up的地方。就不立flag了,总之勤恳的在博客记录自己的学习步伐吧

算法之整数反转

标签:cat   value   博客   new   toc   能力   class   逻辑   long   

原文地址:https://www.cnblogs.com/shinl00/p/11963782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!