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?
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).
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
class Solution{
public:
int reverse(int x){
int length=(int)log10((double)x)+1;//get the length of the number;
int array[length];
array[length-1]=x;
int temp=pow(10,length-1);//we put pow(,) at here to reduce the running time
for(int j=length-1;j>=1;j--){// put each number in a array
array[j-1] = array[j] % temp;
array[j]=(array[j]-array[j-1]) / temp;//here is /
temp/=10;
}
for(int j=0;j<length;j++)
cout<< array[j]<<" ";
cout<<endl;
//------------------if the last number is not zero----------
int result=0;
temp=pow(10,length-1);
if(array[0]!=0){
for(int j=0;j<length;j++){
result+=array[j]*temp;
temp /=10;
}
return result;
}
//-------------if the last number is zero----------------
int num_of_zero=0;
if(array[0]==0){
num_of_zero+=1;
for(int j=1;j<length;j++){
if(array[j]==0)
num_of_zero+=1;
break;//if the number isn't zero,jump out of the cycle
}
}
temp=pow(10,length-num_of_zero-1);
for(int j=num_of_zero;j<length;j++){
result+=array[j]*temp;
temp /=10;
}return result;
}
};
int main() {
int x=5200;
Solution sol;
int result=sol.reverse(x);
cout<< result <<endl;
return 1;
}
下面是很棒的解法
<pre><code class="perl"><span class="keyword">int</span> <span class="keyword">reverse</span>(<span class="keyword">int</span> <span class="keyword">x</span>) {
<span class="keyword">int</span> sign=<span class="keyword">x</span>><span class="number">0</span>?<span class="number">1</span>:-<span class="number">1</span>;
<span class="keyword">x</span>=<span class="keyword">x</span><span class="variable">*sign</span>;
<span class="keyword">int</span> rev=<span class="number">0</span>;
<span class="keyword">while</span>(<span class="keyword">x</span>!=<span class="number">0</span>) {
rev=<span class="number">10</span><span class="variable">*rev</span>+<span class="keyword">x</span><span class="variable">%10</span>;
<span class="keyword">x</span>/=<span class="number">10</span>;
}
<span class="keyword">return</span> rev<span class="variable">*sign</span>;
}</code>