zoukankan      html  css  js  c++  java
  • LeetCode--007--整数反转(java)

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

    示例 1:

    输入: 123
    输出: 321
    

     示例 2:

    输入: -123
    输出: -321
    

    示例 3:

    输入: 120
    输出: 21
    

     解法烂的一批,直接看第二个

     1 class Solution {
     2     public int reverse(int x) {
     3         boolean isNeg = false;
     4         if(x<0){
     5             x = Math.abs(x);
     6             isNeg = true;
     7         }
     8         String s = String.valueOf(x);
     9         Stack<Character> stack= new Stack();
    10         for(int i=0;i<s.length();i++){
    11             stack.push(s.charAt(i));
    12         }
    13         s="";
    14         while(!stack.isEmpty()){
    15             s+=stack.pop();
    16         }
    17         int res=0;
    18         try{
    19             res = Integer.parseInt(s);
    20         }catch(Exception e){
    21             System.out.println(0);
    22             return 0;
    23         }
    24         
    25         if(isNeg){
    26             res = -1 * res;
    27         }
    28         System.out.println(res);
    29         return res;
    30     }
    31 }

     方法2:

    int from -2147483648 to 2147483647

     为了避免反转越界,指定res为long类型。

     1 class Solution {
     2     public int reverse(int x) {
     3         long res = 0;
     4         while(x != 0){
     5            res = res * 10 + x % 10;
     6             x = x / 10;
     7             if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
     8         }
     9         return (int)res;
    10     }
    11 }
  • 相关阅读:
    京东Java面试题(二)
    京东Java面试题(一)
    阿里java面试题
    Java垃圾回收机制
    MyBatis面试题
    Java IO流总结
    Spring中文文档
    Vue.js实战之组件之间的数据传递
    Vue.js实战之Vuex的入门教程
    Vue系列——在vue项目中使用jQuery及其第三方插件
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10529200.html
Copyright © 2011-2022 走看看