zoukankan      html  css  js  c++  java
  • [Leetcode]7. 整数反转

    题目描述

    给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
    如果反转后整数超过 32 位的有符号整数的范围 [−2^31,  2^31 − 1] ,就返回 0。
    假设环境不允许存储 64 位整数(有符号或无符号)。

    • 示例 1:
    输入:x = 123
    输出:321
    
    • 示例 2:
    输入:x = -123
    输出:-321
    
    • 示例 3:
    输入:x = 120
    输出:21
    
    • 示例 4:
    输入:x = 0
    输出:0
    
    • 提示:
    -2^31 <= x <= 2^31 - 1
    

    代码实现

    class Solution {
    
      public int reverse(int x) {
        if (x == Integer.MIN_VALUE || x == Integer.MAX_VALUE) {
          return 0;
        }
        boolean negative = x < 0;
        x = Math.abs(x);
        int res = 0;
        while (x > 0) {
          if (res > Integer.MAX_VALUE / 10) {
            return 0;
          }
          res = res * 10 + x % 10;
          x /= 10;
        }
        return negative ? -res : res;
      }
    
      public static void main(String[] args) {
        System.out.println(new Solution().reverse(123));//321
        System.out.println(new Solution().reverse(-123));//321
        System.out.println(new Solution().reverse(Integer.MAX_VALUE - 1));
        System.out.println(new Solution().reverse(Integer.MIN_VALUE + 1));
      }
    }
    

    按位反转,使用取模运算每次获取到最后一位。要注意负数和整型溢出的问题。

  • 相关阅读:
    面试点滴
    算法之归并排序
    博客园代码高亮样式更换-测试
    MacOS 10.12 设置找不到 任何来源 的话 这么操作 教程
    HTTP代理协议 HTTP/1.1的CONNECT方法
    Linux命令
    Linux命令
    Linux命令
    vmware虚拟机linux桥接模式设置
    GDB调试 (七)
  • 原文地址:https://www.cnblogs.com/strongmore/p/14457312.html
Copyright © 2011-2022 走看看