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 }
  • 相关阅读:
    HDU2059(龟兔赛跑)
    pat 1012 The Best Rank
    pat 1010 Radix
    pat 1007 Maximum Subsequence Sum
    pat 1005 Sign In and Sign Out
    pat 1005 Spell It Right
    pat 1004 Counting Leaves
    1003 Emergency
    第7章 输入/输出系统
    第六章 总线
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10529200.html
Copyright © 2011-2022 走看看