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;
     }
相关文章
相关标签/搜索