题目: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).
答案:
public class Solution { public int reverse(int x) { int rst = 0; while(x != 0){ rst = rst * 10 + x % 10; x = x / 10; } return rst; } }这个答案比较简洁,发现自己已经会用一些比较麻烦的办法。但是这个方法没有考虑溢出
- int reverse(int x,bool &flag) {//flag means if the result is overflow
- int signal=1;
- if (x<0)
- {
- signal=-1;
- }
- int temp,ret=0,newv=0;
- while(x!=0)
- {
- temp = x%10;
- x = x/10;
- if (x!=0)
- {
- newv = newv*10 + temp;
- }
- else//last bit may overflow
- {
- if (signal<0)
- {
- if ( 10*newv + temp >= 0)
- {
- flag = false;
- ret = -1;
- return ret;
- }
- ret = 10 * newv + temp;
- }
- else
- {
- if ( 10*newv + temp <= 0)
- {
- flag = false;
- ret = -1;
- return ret;
- }
- ret = 10 * newv + temp;
- }
- }
- }
- return ret;
- }