LeetCode 7. Reverse Integer


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;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值