[LeetCode]Reverse Integer

原题链接:http://oj.leetcode.com/problems/reverse-integer/

题意描述:

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?

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 };
View Code
原文地址:https://www.cnblogs.com/codershell/p/3601519.html