reverse-integer

来源:互联网 发布:看门狗是什么软件 编辑:程序博客网 时间:2024/05/16 06:18

题目描述
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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).

class Solution {public:    int reverse(int x) {        flag=1;        int sig=1;   //判断是正数还是负数        if(x<0)            {           x=0-x;           sig=0;        }        string str=to_string(x); //转换成字符型        myreverse(str); //翻转        int res=0;        for(int i=0;i!=str.size();++i)            {            res+=(str[i]-'0')*pow(10,str.size()-1-i);        }        if(res<0)   //是否越界 用全局的量进行标示            {            flag=0;            return 0;        }        return sig==1?res:0-res;  //返回    }    void myreverse(string& str)        {        if(str.size()<=1)            return;        int begin=0;        int end=str.size()-1;        while(begin<end)            {            char temp=str[begin];            str[begin]=str[end];            str[end]=temp;            ++begin;            --end;        }    }private:    int flag;};
0 0
原创粉丝点击