LeetCode 7 - Reverse Integer

来源:互联网 发布:巴西统计年鉴数据库 编辑:程序博客网 时间:2024/05/13 20:41

一、问题描述

Description:

Reverse digits of an integer.

For example:

Input x = 123, return 321
Input x = -123, return -321


二、解题报告

本题是对一个整数进行逆转(按整数位),其实思路比较直观:从个位开始,求出每一位并入栈。然后从栈中弹出每一个位,与 10n 相乘并各自相加,直到栈为空为止。

class Solution {public:    int reverse(int x) {        uint64_t n = x>0 ? x:-x;        stack<int> s; // 存储每一位        while(n) {            s.push(n%10);            n = n/10;        }        uint64_t m10 = 1;        while(!s.empty()) {            n += m10 * s.top();            s.pop();            m10 *= 10;        }        if(n > INT_MAX)  // 如果超出范围            return 0;        else            return x>0? n:-n;    }};

注意,逆转以后如果值超出了int的上界,则返回0。





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


0 0