LeetCode記錄之——Reverse Integer,leetcodereverse
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
反轉數位整數。
樣本1:x = 123,返回321
樣本2:x = -123,返回-321
注意:
假定輸入為32位有符號整數。 當反轉的整數溢出時,你的函數應該返回0。
做LeetCode我個人最大的缺點就是上來就幹,因為英語畢竟沒有中文看著方便,導致好多提示根本沒有注意。如本題溢出時返回0。
class Solution { public int reverse(int x) { boolean isAbove=true; StringBuffer sBuffer=new StringBuffer(); int newX=x; if (x < 0) { isAbove = false; x = Math.abs(x); } while (x > 0) { sBuffer.append(x % 10); x = x / 10; } if (newX!=0) { try { if (isAbove) return Integer.parseInt(sBuffer.toString()); else return -Integer.parseInt(sBuffer.toString()); } catch (Exception e) { return 0; } } else return 0; }}
順道來複習下JAVA基礎資料型別 (Elementary Data Type)的數值範圍:
byte的取值範圍為-128~127,佔用1個位元組(-2的7次方到2的7次方-1)
short的取值範圍為-32768~32767,佔用2個位元組(-2的15次方到2的15次方-1)
int的取值範圍為(-2147483648~2147483647),佔用4個位元組(-2的31次方到2的31次方-1)
long的取值範圍為(-9223372036854774808~9223372036854774807),佔用8個位元組(-2的63次方到2的63次方-1)