7. Reverse Integer

  • first attempt
class Solution {
public:
    int reverse(int x) {
        vector<int> ve;
        int remain = abs(x);
        
        int bit;
        if(remain == 0)
            return 0;
        while(remain > 0 )
        {
           bit = remain%10;
           ve.push_back(bit);
           remain/=10;
        }
        int result = 0;
        for(int i = 0; i < ve.size();i++)
        {
            result += ve[i]*pow(10,ve.size()-1-i);
            if(result<0)
                return 0;
        }
        return x>0?result:(-1)*result;
    }
};
  • second attempt
class Solution {
public:
    int reverse(int x) {
        
        int remain = abs(x);
        long result = 0;
        int bit;
        if(remain == 0)
            return 0;
        while(remain > 0 )
        {
           bit = remain%10;
           result = result*10+bit;
           if(result>INT_MAX)
                return 0;
           remain = remain/10;
        }
        return (x>0?result:(-1)*result); 
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 题目:7. Reverse Integer 注意这里如果y是int,那么 Integer.MAX_VALUE/10...
    Reflection_阅读 186评论 0 0
  • Description: Reverse digits of an integer.Example1: x = 1...
    Icytail阅读 209评论 0 0
  • Reverse digits of an integer. Example1: x = 123, return 3...
    雒霭阅读 541评论 0 48
  • 最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正. 问题描述: Revers...
    ciantian阅读 348评论 0 1
  • 那些垛 ——乡村怀旧系列散文之“垛” 火山 偶尔去孟奇兄的琴馆听古琴,看到他画的一些乡村油画,其中关于草垛的画作,...
    朱明云阅读 387评论 0 7

友情链接更多精彩内容