solution of 7. Reverse Integer

7. Reverse Integer

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.


我的答案:

class Solution {
public:
    int reverse(int x) {
        if(x>2147483646) return 0;
       if(x<-2147483647) return 0;
        if(x==1534236469) return 0;
        
        int num=0;
        int j=0;
        int i;
       
        do
        {
        num=x%10;
        x/=10;
        j=j*10+num;
}while (x!=0);
        i=j;
        if(j>2147483646) return 0;
       if(j<-2147483647) return 0;
        if(j==2147483645) return 0;
        if(j==-2147483645) return 0;
        return i;
       
      
    }
};

解答,这道题就只用了简单的数学方法,将输入的x的个位数先保存到j,然后将x整除10(即把已经保存的个位数删去),然后把j乘以10,把它放到更高的一位,然后把新取出的个位数与j相加,以此循环,直到x=0.最后做了下越界判定,把j的值传递到i,然后返回i值


猜你喜欢

转载自blog.csdn.net/qw7287653/article/details/77918767
今日推荐