Skip to content

Latest commit

 

History

History
88 lines (76 loc) · 2.16 KB

7. Reverse Integer.md

File metadata and controls

88 lines (76 loc) · 2.16 KB

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: 21

Note:

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Sulution

  • mine
    • Java
      • String Runtime: 2 ms, faster than 23.53%, Memory Usage: 33.7 MB, less than 11.66%

        public int reverse(int x) {
            boolean negative = x < 0;
            x = Math.abs(x);
            String str = String.valueOf(x);
            StringBuilder sb = new StringBuilder();
            for (int i = str.length() - 1; i >= 0; i--) {
                sb.append(str.charAt(i));
            }
            try {
                int res = Integer.parseInt(sb.toString());
                return negative ? 0 - res : res;
            } catch (Exception e) {
                return 0;
            }
        }
        
      • Math Runtime: 1 ms, faster than 100.00%, Memory Usage: 33.8 MB, less than 11.11%

        public int reverse(int x) {
            if (x == Integer.MAX_VALUE || x == Integer.MIN_VALUE){
                return 0;
            }
            int result = 0;
            while (x != 0) {
                int tail = x % 10;
                int newResult = result * 10 + tail;
                if ((newResult - tail) / 10 != result) {
                    return 0;
                }
                result = newResult;
                x = x / 10;
            }
            return result;
        }
        

  • the most votes

    • Math Runtime: 1 ms, faster than 100.00%, Memory Usage: 33.5 MB, less than 11.66%
      public int reverse(int x) {
          long rev= 0;
          while( x != 0){
              rev= rev*10 + x % 10;
              x= x/10;
              if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE)
                  return 0;
          }
          return (int) rev;
      }