zoukankan      html  css  js  c++  java
  • ReverseInteger:实现int整数的反转

    原文链接

    Given a 32-bit signed integer, reverse digits of an integer.
    Example 1:
    Input: 123
    Output: 321
    Example 2:
    Input: -123
    Output: -321
    Example 3:
    Input: 120
    Output: 21
    Note:
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    class Solution1 {
        public int reverse(int x) {
            while (x % 10 == 0) {
                x /= 10;
            }
            boolean tag = false;
            if (x < 0) {
                tag = true;
                x = x * -1;
            }
            String s = String.valueOf(x);
            char[] ch = s.toCharArray();
            for (int i = 0;i < ch.length;i++) {
                int k = ch.length - i - 1;
                if (k < ch.length / 2) break;
                char cc = ch[i];
                ch[i] = ch[k];
                ch[k] = cc;
            }
            String re = String.valueOf(ch);
            int RI = Integer.valueOf(re);
            if (tag) RI = RI * -1;
            System.out.println(RI);
            return RI;
        }
    }
    /*
    * 1. 前几天刚做了字符反转的,想当然就以为可以直接拿来用。结果却和出题人意图相差甚远.Solution1的方案对于小部分的测试数据可行,但是当前的状态是行不通的,也没有继续对此进行修改完善.
    * 2. 一开始做的时候下面的Solution思路类似,但是因为对算法的逻辑思路不是很透彻,写出来的代码肯定很杂乱繁琐。下面的这个解题思路有参考到Discussion中的一个答案.
    * 3. 昨晚做出来之后一直不晓得哪里出错了,没有意识到int类型的边界范围,还特别纳闷为啥断点跟踪的时候1534236469这个数字最后一下子就变了.根本没有考虑过怎么处理"int类型数据溢出"问题
    *   上网搜索了一下之后才晓得怎么判断int类型问题。https://www.cnblogs.com/hesiyi/p/6963435.html
    *
    * */
    class Solution {
        public int reverse(int x) {
            int sum = 0;
            int t = 0;
            while (x != 0) {
                if ((sum * 10L) > Integer.MAX_VALUE || (sum * 10L) < Integer.MIN_VALUE)
                    return 0;
                sum = sum * 10 + x % 10;
                x = x / 10;
            }
            return sum;
        }
    }
    public class ReverseInteger {
        public static void main(String[] args) {
            Solution1 solu = new Solution1();
            int kkk = solu.reverse(-214748364); // -2147483648,1534236469
            System.out.println(kkk);
        }
    }
    

    关于int类型数据溢出的问题,移步博客:java-int数据的溢出

    I can
  • 相关阅读:
    idea配置tomcat运行按钮置灰,下拉没有自定义的tomcat选项
    配置多版本jdk,自由切换jdk版本
    五年经验程序员告诉你,如何确定自己是否适合做程序员
    你的编程能力从什么时候开始突飞猛进?
    10 个提升效率的Linux小技巧
    8 种经常被忽视的 SQL 错误用法,你有没有踩过坑?
    十大优秀编程项目,让你的简历金光闪闪
    一文掌握 Lambda 表达式
    一文详解微服务架构(一)
    Java的参数传递是「按值传递」还是「按引用传递」?
  • 原文地址:https://www.cnblogs.com/leonwen/p/10486730.html
Copyright © 2011-2022 走看看