[LeetCode]Reverse Integer

Reverse digits of an integer.

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

考虑输入是abc,返回结果是cba,那么假设用除法(除以10)取余数操作的话,是先入先出的操作(第一次入abc%10=c),因此选择使用队列。

复习队列的方法有q.size(),q.front(),q.pop(),q.push().队列的声明queue<int> q;

代码:

class Solution {
public:
    int reverse(int x) {
        int mul =   10,start    =   x,ret   =   0;
        queue<int> q;
        for(;start  !=   0;)
        {//直到余数为0,停止
            q.push(start%mul);
            start   =   start/mul;//应当除以10,取整,
        }
        for(;0!=q.size();)
        {
            ret =   10  *   ret +   q.front();
            q.pop();
        }
        return ret;
    }
};


原文地址:https://www.cnblogs.com/lcchuguo/p/4503072.html