標籤:sse sed ogre func code binding within 注意 else
題目:Reverse Integer
難度:Easy
題目內容:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
翻譯:給定一個32位簽名整數,一個整數的反向數字。
注意:
假設我們正在處理一個只能容納32位的整形數值。出於這個問題的目的,當反轉整數溢位時函數返回0。
Example 1:
Input: 123Output: 321
Example 2:
Input: -123Output: -321
Example 3:
Input: 120Output: 21
我的思路:用List將數值從低位依次取出到高位,用list的第一個記錄此整數的符號。最後輸出的時候用一個boolean來判斷是否前面全為零,然後跳過此零。
My Code:
1 public int reverse(int x) { 2 List<Integer> ans = new ArrayList<Integer>(); 3 if (x < 0) { 4 ans.add(0); 5 x = -x; 6 } else if (x > 0) { 7 ans.add(1); 8 } else { 9 return 0;10 }11 while (x != 0) {12 ans.add(x%10);13 x = x / 10;14 }15 int y = 0;16 boolean tag = false; 17 for (int i = 1;i < ans.size(); i++) {18 if (tag == false && ans.get(i) == 0) {19 continue;20 } else {21 tag = true;22 }23 y += ans.get(i);24 if (i < ans.size() - 1) y *= 10;25 }26 y = ans.get(0) == 1 ? y : -y;27 return y;28 }
結果:1027 / 1032 test cases passed.
Input:1534236469Output:1056389759Expected:0 意思是反轉之後需要判斷是否溢出。弄了半天都沒思緒,因為反轉後一位一位乘以10後就直接溢出然後變為另外一個值,不好比較是否越界。。。。原諒我這個笨腦闊吧?? 編程中問題:1、boolean類型再賦值的時候不小心用了 == ,結果LeetCode報錯:not a Statement
答案:
1 public int reverse(int x) { 2 int result = 0; 3 while (x != 0) 4 { 5 int tail = x % 10; 6 int newResult = result * 10 + tail; 7 if ((newResult - tail) / 10 != result) 8 { return 0; } 9 result = newResult;10 x = x / 10;11 }12 return result;13 }
還有沒有天理了。。。。13行就搞定了?!
答案思路:
1、因為負數求餘數和除以10後還是負數,所以並不需要將符號進行記錄。
2、因為若當前反轉第一個數為零,乘以10還是零,所以也不需要用list進行記錄。
3、因為乘以10再加上一個值後可能溢出無法與max值相比較,那麼就反過來用(max-tail)/ 10 與當前值進行比較!哎 我真笨的可以。。
4、可以直接用新值反推舊值進行比較,變了說明,這樣就不用對tail進行正負判斷(當tail為負的時候就應該是(min-tail)/10 > result 為正應該是(max-tail)/10 < result )
LeetCode第[7]題(Java):Reverse Integer 標籤:數學