ogv

Untitled

ogv
Nov 2nd, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. // Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
  2. class Solution {
  3.     public int reverse(int x) {
  4.         if (x == 0) return 0;
  5.         if (x == Integer.MIN_VALUE) return 0;
  6.        
  7.         if (x < 0) return -reverse(-x);
  8.        
  9.         int r = 0;
  10.        
  11.         while (x > 0) {            
  12.             int d = x % 10;
  13.             r = 10 * r + d;
  14.            
  15.             if (r % 10 != d) return 0;
  16.                                  
  17.             x /= 10;
  18.         }
  19.        
  20.         return r;
  21.     }
  22. }
  23.  
  24. // Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
  25. class Solution {
  26.     final int MAX_10_MULTIPLIER = Integer.MAX_VALUE / 10;
  27.    
  28.     public int reverse(int x) {
  29.         if (x == 0) return 0;
  30.         if (x == Integer.MIN_VALUE) return 0;
  31.        
  32.         if (x < 0) return -reverse(-x);
  33.        
  34.         int r = 0;
  35.        
  36.         while (x > 0) {
  37.             int d = x % 10;
  38.            
  39.             if (r > MAX_10_MULTIPLIER) return 0;
  40.             r *= 10;
  41.             if (r > Integer.MAX_VALUE - d) return 0;
  42.             r += d;        
  43.                                  
  44.             x /= 10;
  45.         }
  46.        
  47.         return r;
  48.     }
  49. }
Add Comment
Please, Sign In to add comment