【LeetCode007算法/编程练习C++】数字逆序(atol)

来源:互联网 发布:印度入侵中国边界知乎 编辑:程序博客网 时间:2024/06/14 23:50

7. Reverse Integer

 //溢出的话设为0
  • Total Accepted: 192898
  • Total Submissions: 815127
  • Difficulty: Easy
  • Contributors: Admin

Reverse digits of an integer.

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

click to show spoilers.

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.


注意事项:

1.超过2147483647要设为0

2.string转long可以用atol,类似的转int用atoi

3.long要比long int快很多,用long int需要16ms但long只需要6ms

 --------------------------------答案分割线-----------------------------

利用了string,转换起来方便了很多。

class Solution {public:int reverse(int x) {string s = to_string(x >= 0 ? x : -x);string temp="";for (int i = 0; i<s.size(); i++) {temp+= s[s.size() - 1 - i];}long pre_result = 0;pre_result = atol(temp.c_str());if (pre_result > 2147483648&&x<0 )return 0;else if (pre_result > 2147483647 && x >= 0)return  0;else return int((x>=0?1:-1)*pre_result);}};

运行结果如图,可以看出来速度还是可以的……



下面分享Top Solution里看到的非常优雅的非常简洁的方法://看着好简洁啊,竟然只有7行………………

class Solution {public:    int reverse(int x) {        long long res = 0;        while(x) {            res = res*10 + x%10;            x /= 10;        }        return (res<INT_MIN || res>INT_MAX) ? 0 : res;    }};
再刷一题去次饭……



0 0