LeetCode 7. Reverse Integer

来源:互联网 发布:最近的网络流行词 编辑:程序博客网 时间:2024/05/18 13:44


Description:


Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321


Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


这题因为相对容易,以下是我的想法,算法显而易见但是速度不够快

Submission Details
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 35 ms

class Solution {public:    int reverse(int x) {        long long res = 0;        int tmp;        while(x != 0) {            tmp = x % 10;            res = res * 10 + tmp;            x /= 10;        }        if (res > INT32_MAX || res < INT32_MIN) {            return 0;        }        return (int)res;    }};


从女神那里得到了一个较优的方法,string转long long配合reverse()函数
学到两个新的方法:
1. reverse() 函数

template<class BidirectionalIterator>   void reverse(      BidirectionalIterator _First,       BidirectionalIterator _Last   );


其中:
_First
指向第一个元素的位置的双向迭代器在元素交换的范围。
_Last
指向通过最终元素的位置的一双向迭代器在元素交换的范围。
2. std:: to_string()函数, 可以将以下数据类型转化为string

string to_string (int val);string to_string (long val);string to_string (long long val);string to_string (unsigned val);string to_string (unsigned long val);string to_string (unsigned long long val);string to_string (float val);string to_string (double val);string to_string (long double val);


3. std:: stoll()函数 类似于stoi() 以及stof()函数,将string类型转化为long long等类型

long long stoll (const string&  str, size_t* idx = 0, int base = 10);long long stoll (const wstring& str, size_t* idx = 0, int base = 10);


Submission Details
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 18 ms

class Solution {public:    int reverse(int x) {        string s = to_string(x);        if(s[0] == '-')            std::reverse(s.begin() + 1, s.end());        else            std::reverse(s.begin(), s.end());        long long int temp = stoll(s);        if(temp > 2147483647 || temp < -2147483648)            return 0;        return (int)temp;    }};
原创粉丝点击