1. 程式人生 > >LeetCode--Reverse Integer

LeetCode--Reverse Integer

iss com ack ostream 題目 width 報告 pull stack

//#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 Integer

Total Accepted: 17307 Total Submissions: 43519My Submissions

Reverse digits of an integer.

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

click to show spoilers.


LeetCode--Reverse Integer