首页 > 其他 > 详细

Reverse Integer

时间:2016-01-03 22:36:04      阅读:240      评论:0      收藏:0      [点我收藏+]

Reverse digits of an integer.

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

click to show spoilers.

 

Subscribe to see which companies asked this question

两种方法,第一种比较耗时间,应该是在转换为字符串的时候浪费了时间

class Solution {
public:
    
    void reverse_str(string &s, int begin, int end)
    {
        int i ,j;
        char c;
        for (i=begin,j=end;i<j;i++,j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
            
        }
    }
    int reverse(int x) {
        if (x>=0 && x<=9)
            return x;
        stringstream ss;
        ss << x;
        string str = ss.str();
        int len = str.size();
        if (x > 0)
        {
            reverse_str(str,0,len-1);
        }
        else
        {
            reverse_str(str,1,len-1);
        }
        stringstream sss(str);
        double r =0;
        sss >> r;
        if (r>INT_MAX || r<INT_MIN) {
            r = 0;
        }
        return (int)r;
    }
};

 

class Solution {
public:
    
    void reverse_str(string &s, int begin, int end)
    {
        int i ,j;
        char c;
        for (i=begin,j=end;i<j;i++,j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
            
        }
    }
    int reverse(int x) {
        if (x>=0 && x<=9)
            return x;
        stringstream ss;
        ss << x;
        string str = ss.str();
        int len = str.size();
        if (x > 0)
        {
            reverse_str(str,0,len-1);
        }
        else
        {
            reverse_str(str,1,len-1);
        }
        stringstream sss(str);
        double r =0;
        sss >> r;
        if (r>INT_MAX || r<INT_MIN) {
            r = 0;
        }
        return (int)r;
    }
};

 

 

Reverse Integer

原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5097307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!