給一個 32bit 有正負號的整數,返回反轉過後的數字。
LeetCode 題目連結
https://leetcode.com/problems/reverse-integer
題目
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.
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.
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.
Accept 作法
要考慮溢位問題,還有負號永遠擺前面,以及遇到 0 在前面反轉後都不顯示。
Runtime: 2 ms
Memory: 36.9 MB
Java
Runtime: 2 ms
Memory: 36.9 MB
class Solution { class Solution { public int reverse(int x) { String intStr = String.valueOf(x); StringBuilder result = new StringBuilder(); boolean isCons = false; for(int i = 0; i< intStr.length();i++){ if(intStr.charAt(i) == '-'){ result.append('-'); isCons = true; }else{ if(isCons){ if(intStr.charAt(intStr.length() - i) != '-'){ result.append(intStr.charAt(intStr.length() - i)); } }else{ result.append(intStr.charAt(intStr.length() - 1 - i)); } } } try{ int resultInt = Integer.valueOf(result.toString()); return resultInt; }catch(Exception e){ return 0; } } } }
官方的答案更簡單。我果然還是想的太冗長了。
class Solution { public int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言