Leetcode题解 7. Reverse Integer
2016-04-15 14:44
337 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
要考虑溢出的情况,用try catch捕获异常,感觉这道题好无聊。
别人的做法,感觉更好,学习一下。
Example1: x = 123, return 321
Example2: x = -123, return -321
要考虑溢出的情况,用try catch捕获异常,感觉这道题好无聊。
public int reverse(int x) { String xx = String.valueOf(x); try { int flag = 0; StringBuilder sb = new StringBuilder(); if (xx.startsWith("-")) { flag = 1; } Stack<Character> mStack = new Stack<Character>(); for (int i = (flag == 0 ? 0 : 1); i < xx.length(); i++) { mStack.push(xx.charAt(i)); } while (mStack.size() > 0) { sb.append(mStack.pop()); } return flag == 0 ? Integer.parseInt(sb.toString()) : -Integer.parseInt(sb.toString()); } catch (Exception exception) { System.out.println("This is not an integer"); } return 0; }
别人的做法,感觉更好,学习一下。
public int reverse(int x) { boolean flag = true; if(x < 0){ flag = false; x = x*-1; } long res = 0; while(x > 0){ res = res *10 + x%10; x = x / 10; } if(res > Integer.MAX_VALUE){ return 0; } if(flag){ return (int)res; }else{ return (int)res * -1; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解