码迷,mamicode.com
首页 > 其他好文 > 详细

7. Reverse Integer

时间:2020-03-27 19:48:05      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:ali   back   store   eal   returns   within   problem   class   while   

Problem:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231, 231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路

Solution (C++):

int reverse(int x) {
    bool flag = 0;
    long long l = 0;
    if (x == INT_MIN) l = unsigned(INT_MIN);
    else if (x < 0) {
        flag = 1;
        l = -x;
    }
    else l = x;
    vector<int> reverse;
    int last = 0;
    while (l) {
        last = l % 10;
        l /= 10;
        reverse.push_back(last);
    }
    for (int i = reverse.size()-1; i >=0; --i) {
        l += reverse[i] * pow(10, reverse.size()-1-i);
    }
    if (flag) l = -l;
    if (l < INT_MIN || l > INT_MAX)     return 0;
    else return l;
}

性能

Runtime: 4 ms??Memory Usage: 6.3 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

7. Reverse Integer

标签:ali   back   store   eal   returns   within   problem   class   while   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12583780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!