栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

力扣——整数反转

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣——整数反转

整数反转

给你一个 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

提示:

-231 <= x <= 231 - 1


 public int reverse(int x){
        int res=0;
        while(x!=0){
            int tmp=res*10+x%10;
            if(tmp/10!=res){
                //判断是否溢出
                return 0;
            }
            res=tmp;
            x=x/10;

        }
        return res;
    }

实现调用:

package com.kk;

import java.util.Scanner;

public class IntegerInversion {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x=scanner.nextInt();
        reverse(x);
        System.out.println(reverse(x));
    }
    public static int reverse(int x){
        int res=0;
        while(x!=0){
            int tmp=res*10+x%10;
            if(tmp/10!=res){
                //判断是否溢出
                return 0;
            }
            res=tmp;
            x=x/10;

        }
        return res;
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/286899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号