C/C++教程

LeetCode 整数反转

本文主要是介绍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

提示:
-231 <= x <= 231 - 1

除10取余,数学推导有点东西

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while(x != 0){
            if(rev < Integer.MIN_VALUE / 10 || rev > Integer.MAX_VALUE / 10)
            //此处为相关数学推导,有点难度
                return 0;
            int digit = x % 10;
            x /= 10; 
            rev = rev * 10 + digit;
        }
    return rev;
    }
}

转载:LeetCode :https://leetcode-cn.com/problems/reverse-integer/solution/

这篇关于LeetCode 整数反转的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!