leetcode 7 Reverse Integer

題目詳情

Given a 32-bit signed integer, reverse digits of an integer.

題目要求咱們給出一個數的翻轉數
 
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21git

想法

  • 這道題主要的坑就是在於一個int數值的輸入,在進行翻轉操做以後,不必定還符合int的範圍,可能會形成異常。
  • 咱們能夠經過每次得到整數除10的餘數,來肯定當前整數的最後一位。

解法

public int reverse(int x) {
         long res = 0;
         
         while(x != 0){
             int tail = x % 10;
             res = res*10 + tail; 
             if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE){
                 return 0;
             }
             x = x/10;
         }
         return (int)res;
     }
相關文章
相關標籤/搜索