[LeetCode]Reverse Integer
2014-03-14 23:53 庸男勿扰 阅读(166) 评论(0) 编辑 收藏 举报原题链接:http://oj.leetcode.com/problems/reverse-integer/
题意描述:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
题解:
这道题主要考到了如何取出整数的每一位,比较简单。
1 class Solution { 2 public: 3 int reverse(int x) { 4 bool flag = true; 5 if(x<0){ 6 flag = false; 7 x = -x; 8 } 9 10 queue<int> q; 11 int ret=0,cur; 12 13 int len=0; 14 15 while(x!=0){ 16 q.push(x%10); 17 len++; 18 x /=10; 19 } 20 for(int i=len-1; i>=0; i--){ 21 cur = q.front(); 22 q.pop(); 23 ret += cur*pow(10,i); 24 } 25 if(!flag) 26 ret = -ret; 27 28 return ret; 29 } 30 };
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~