LeetCode記錄之——Reverse Integer,leetcodereverse

來源:互聯網
上載者:User

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)

  

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.