刷题-力扣-7

7. 整数反转

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

示例 1:

输入:x = 123
输出:321

示例 2:

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

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

提示:

  • -231 <= x <= 231 - 1

题目分析

  1. 整数反转,从末尾数字先出
  2. 利用求余获得最后一位数字,求除获得剩下的数字
  3. 循环直到x变为零
  4. 如果long转化为int后不变,则返回long
  5. 如果long转化为int后改变,说明溢出,返回0

代码

class Solution {
public:
    int reverse(int x) {
        if (x == 0) return x;
        long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x = x / 10;
        }
        return (int)res == res ? res : 0;
    }
};

用时30min

原文地址:https://www.cnblogs.com/HanYG/p/14263973.html