LeetCode 007 Reverse Integer - Java

來源:互聯網
上載者:User

標籤:buffer   boolean   pre   負數   lock   func   string   solution   span   

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.

 

定位:簡單題

將輸入的數反轉輸出,注意的是負數符號保持在最前,反轉後的值超出int_32bit範圍輸出0。

簡單的將傳如的數分離符號後用StringBuffer進行反轉,然後轉化為int,此時嘗試抓取NumberFormatException的錯誤,如有直接為0。

 

Java實現:

 1 public class Solution { 2     public int reverse(int x) { 3         boolean isNev=false; 4         if(x<0){ 5             x=-x; 6             isNev=true; 7         } 8         StringBuffer stringBuffer=new StringBuffer(String.valueOf(x)); 9         stringBuffer=stringBuffer.reverse();10         int y;11         try{12             y=Integer.parseInt(stringBuffer.toString());13         }catch (NumberFormatException e){14             y=0;15         }16         if(isNev){17             y=-y;18         }19         return y;20     }21 }

 

LeetCode 007 Reverse Integer - Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.