LeetCode : 7 Reverse Integer C++

Description

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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

分析

题意就是给定一个有符号整数,将其每一位倒置后输出。如果导致后超出了32位所能表达的最大或最小数字,就直接返回0

代码1

自以为机智的用了c++ string中数字转字符串和字符串转数字的函数 to_string() 和 atoll,好理解是好理解,代码并不简洁:

#include<string>
#include<limits>
#include<vector>
class Solution {
public:
    int reverse(int x) {
        if ((x < 10 && x>0) || (x<0 && x>-10))return x;
    bool neg = (x < 0) ? true: false;
    if (x < 0)x = -x;
    string strx = to_string(x);
    int len = strx.length();
    if (len > 32)return 0;
    vector<char>vec;
    for (int i = len - 1; i >= 0; i--)
    {
        vec.push_back(strx[i]);
    }
    string rev = (neg) ? "-" : "";
    vector<char>::iterator ite;
    for (ite = vec.begin(); ite != vec.end(); ite++)
        rev += *ite;
    long long ans = atoll(rev.c_str());
    if (ans > INT_MAX || ans < INT_MIN)return 0;
    else return (int)ans;

    }
};

代码2

晚上随便浏览一下就发现非常简洁的做法。其实直接取模就好了,是很常见的类型,每次乘以10再加上当前位;为了保证不溢出在每次乘10之前判断一下

int reverse(int x) {
    int y = 0;
    while (x!=0)
    {
        int d = x % 10;
        if (y > INT_MAX / 10 || y < INT_MIN / 10)return 0;
        y = y * 10 + d;
        x /= 10;
    }
    return y;
}

数字位相关的操作,很多都是取模运算来解决的,对十进制而言,每次*10+digit即可,不需要从10的多少次方开始QAQ

猜你喜欢

转载自blog.csdn.net/beforeeasy/article/details/79668049
今日推荐