leetcode题目7

整数翻转

中等

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

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

思路

第一种方法,将数转为String,通过StringBuffer对末尾的字符进行输入后重新输出。
第二种方法,将数对其取余后赋值
检测方法都同理,在检测到超出整数的范围后就输出0;

代码:

StringBuffer输出

public static int reverse(int x) {
        Long res=0L;

        String NewX = String.valueOf(x);
        StringBuilder StB = new StringBuilder();
        int note = 0;
        if(NewX.charAt(0)=='-'){
             note= 1;
             StB.append(NewX.charAt(0));
        }
        for(int i=NewX.length()-1;i>=note;i--){
            StB.append(NewX.charAt(i));
            
        }
        res = Long.valueOf((StB.toString()));
        if (res<= -2147483648  ||res>= 2147483647){
            return 0;
        }
        return Math.toIntExact(res);

    }

取余赋值输出

class Solution {
     public static int reverse(int x) {
        int res = 0;
        while(x!=0){
            int tmp = x%10;
            
           //判断是否 大于 最大32位整数
            if (res>214748364 || (res==214748364 && tmp>7)) {
                return 0;
            }
            //判断是否 小于 最小32位整数
            if (res<-214748364 || (res==-214748364 && tmp<-8)) {
                return 0;
            }

            res = res*10+tmp;
            x = x/10;
        }
        return  res;

    }
 }

相关推荐

  1. leetcode题目7

    2024-05-13 11:00:04       14 阅读
  2. LeetCode-hot100题解—Day7

    2024-05-13 11:00:04       9 阅读
  3. leetcode 字符串相关题目

    2024-05-13 11:00:04       32 阅读
  4. 自练题目leetcode

    2024-05-13 11:00:04       21 阅读
  5. leetcode自练题目

    2024-05-13 11:00:04       20 阅读
  6. leetcode】栈题目总结

    2024-05-13 11:00:04       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-13 11:00:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-13 11:00:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-13 11:00:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-13 11:00:04       20 阅读

热门阅读

  1. 【二叉树算法题记录】404. 左叶子之和

    2024-05-13 11:00:04       12 阅读
  2. 安卓LeakCanary研究

    2024-05-13 11:00:04       15 阅读
  3. SQLite 语法大全

    2024-05-13 11:00:04       14 阅读
  4. codeforce#939 (div2) 题解

    2024-05-13 11:00:04       28 阅读
  5. 什么是结对编程?

    2024-05-13 11:00:04       12 阅读
  6. Caffe: Convolutional Architecture for Fast Feature Embedding

    2024-05-13 11:00:04       14 阅读
  7. Docker 部署Redis

    2024-05-13 11:00:04       17 阅读
  8. 旅行商要点和难点实际应用和代码案例代码解析

    2024-05-13 11:00:04       14 阅读
  9. Docker 快速搭建 Kafka 集群

    2024-05-13 11:00:04       13 阅读