LeetCode--Reverse Integer
//#include <iostream> #include <cmath> #include <stack> //using namespace std; //const int MAXN=10; //int Stack[MAXN]; stack<int> s; class Solution { public: int getNumber(int x) { //int lengthOfStack=0; //int i=0; while(x) { //cout<<x%10; //Stack[i++]=x%10; s.push(x%10); //lengthOfStack++; x=x/10; } int sum=0; //int val=lengthOfStack-1; //int val=s.size()-1; int val=0; //for(int j=lengthOfStack-1;j>=0;j--) //{ // sum+=Stack[j]*pow(10.0,val); // val--; //} while(s.empty()!=true) { //int temp=s.pop(); int temp=s.top(); s.pop(); sum+=temp*pow(10.0,val); val++; } return sum; } int reverse(int x) { if(x>=0) { return getNumber(x); } else { //int y=-x; //cout<<"-"; return (-getNumber(-x)); } } };
做完之后,回头搜了下别人的报告。
int reverse(int x) { int result = 0; while (x) { result = result*10 + x%10; x /= 10; } return result; }
补充题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321