前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode】Reverse Integer

【leetcode】Reverse Integer

作者头像
阳光岛主
发布2019-02-19 11:27:50
5200
发布2019-02-19 11:27:50
举报
文章被收录于专栏:米扑专栏

Question : 

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).

Anwser 1 :

代码语言:javascript
复制
class Solution {
public:
    int reverse(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int ret = 0;
        
        int div = 1;
        bool flag = false;
        if(x < 0) {         // flag a negative
            flag = true;
            x = -x;
        }
        
        queue<int> Q;
        while(x > 0){       
            int mod = x % 10;   // from low digit to high
            Q.push(mod);
            
            x /= 10;
            div *= 10;
        }
        
        while(!Q.empty()){
            int mod = Q.front();    // pop low digit
            Q.pop();
            
            div /= 10;
            ret = ret + mod * div;
        }
        
        return flag ? -ret : ret;
    }
};

Anwser 2 :

代码语言:javascript
复制
class Solution {
public:
    int reverse(int x) {
        int res = 0;
        
        bool flag = x < 0 ? true : false;
        x = flag ? -x : x;
        
         while (x > 0) {       // don't care positive or negetive
             res = res * 10 + x % 10;   // get lowest digit then multi 10
             x /= 10;
         }
         
         return flag ? -res : res;
    }
};

more simple :

代码语言:javascript
复制
class Solution {
public:
    int reverse(int x) {
        int res = 0;
         
         while (x != 0) {       // don't care positive or negetive
             res = res * 10 + x % 10;   // get lowest digit then multi 10
             x /= 10;
         }
         
         return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013年04月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档