【leetcode】7. Reverse Integer

來源:互聯網
上載者:User

標籤:

題目描述:

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

解題思路:

這道題比較簡單,只要注意兩個問題:1,輸入可能有123,-123兩種情況。2,可能會出現值溢出的情況,所以先用long類型處理,決定沒有溢出後再轉換為int

具體代碼:

 1 public static int reverse(int x) { 2         String s =""+x; 3         char[] array=s.toCharArray(); 4         if(array[0]==‘-‘){ 5             reverse(array,1); 6             Long num=Long.valueOf(new String(array)); 7             if(num<Integer.MIN_VALUE){ 8                 return 0; 9             }10             return Integer.valueOf(new String(array));11             12         }13         else{14             reverse(array,0);15             Long num=Long.valueOf(new String(array));16             if(num>Integer.MAX_VALUE){17                 return 0;18             }19             return Integer.valueOf(new String(array));20         }21 22    }23    public static void reverse(char[] array,int from){24        int to = array.length-1;25        while(from<to){26            char ch=array[from];27            array[from]=array[to];28            array[to]=ch;29            from++;30            to--;31        }32    }

 

【leetcode】7. Reverse Integer

聯繫我們

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