leetcode解题报告7. Reverse Integer

来源:互联网 发布:儿童桌面软件 编辑:程序博客网 时间:2024/05/17 03:26

leetcode解题报告7. Reverse Integer

题目地址

难度是easy

题目描述

翻转数字,看例子就很明白了
Example1: x = 123, return 321
Example2: x = -123, return -321

我的思路

很简单的模拟类题目,按照操作就行了。关键是会利用求余运算和除法,把一个数,把它的每一位求出来。

另外要注意溢出的情况。题目是要求当要求溢出时,返回0

我的代码

class Solution {public:    int reverse(int x) {        long long ans = 0;        int flag = 1;        if (x < 0) {            flag = -1;            x = -x;        }        while (x > 0) {            int t = x % 10;            ans = ans *10 + t;            x /= 10;        }        if (ans > 2147483647 || ans < -2147483648) {            return 0;        }        return flag * ans;    }};

阅读官方题解

没有官方题解,从网上信息来看,题目比较简单,没有什么特别的想法。

思想核心总结

注意处理边界情况,比如溢出

0 0
原创粉丝点击