反转整数
2013-10-05 23:17
225 查看
/*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). */ #include <iostream> #include <exception> #include <limits> class Solution { public: int reverse(int x) { if(x==0) return 0; bool sig=true; unsigned long long result=0; unsigned long long xx; if(x>0) xx=x; else { sig=false; xx=-1*x; } while(xx) { result=result*10+xx%10; xx/=10; } if(sig && result>std::numeric_limits<int>::max()) throw std::exception(); else if(!sig && result*(-1)<std::numeric_limits<int>::min()) throw std::exception(); else if(sig) return result; else return (-1)*result; } }; int main(int argc,char* argv[]) { int x=231; Solution s; std::cout<<s.reverse(x)<<std::endl; return 0; }
相关文章推荐
- 输入一个整数,将各位数字反转后输出
- 反转整数
- 反转一个整数 递归/原创
- GEEK编程练习— —反转整数
- 【我解C语言面试题系列】006 按位反转整数问题
- 整数二进制比特反转
- LeetCode第七题--反转32位的整数
- 反转整数的每一位(reverse integer)
- LeetCode-7-反转整数-c# 版本
- 整数反转的程序
- 整数的二进制形式数反转
- 按位反转字符串与整数
- 对一个整数按位反转
- 整数反转的递归算法
- 整数二进制位反转
- LintCode入门-37-反转一个3位整数
- Leetcode:Reverse Integer ,整数反转
- lintcode-413-反转整数
- LeetCode算法题:JAVA实现整数反转reverse integer
- 对一个整数按位反转