7.Reverse Integer

来源:互联网 发布:万网二手域名交易平台 编辑:程序博客网 时间:2024/06/04 19:48

题目:

Reverse digits of an integer.

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

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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

思路:

整数是4字节,32位的,所以其取值范围是:-(2^31)~(2^31)-1,最大范围是2147483648。(无符号位,0~(2^32)-1;有符号位,-(2^31)~(2^31)-1)。

(1)传入原数是负,则获得其相反数;为正,则不变,记为整数。(接下来先不考虑符号)

(2)先把整数转换为字符数组(a[0]存储个位数,a[1]存储十位数.........)。(由于其十进制最大位数不会超过10,所以字符数组长度为10就可以了,节省空间)

(3)double是8字节的,64位,所以其容量包含:整数的范围 和 整数对应相反数的范围;容量足够大,利用这个技巧。

          把字符数组逆向转换为双精度浮点型存储起来,此时已获得相反数,记为reverse。

(4)若原数为负,则reverse 大于等于 ((2^31)-1),超过最大范围,返回0;否则返回reverse。

          若原数为正,则(-reverse)小于(-(2^31)),超过最小范围,返回0;否则返回(-reverse)。

注意:

         C语言中,求余运算%两边的数据都必须是整数,不能是浮点数,所以,对于最小值-2147483648,其相反数已经超出整数的范围,因此不能用整数变量进行存储,但是又不能用double型数据进行%运算,所以只能做一个特殊处理,单独用if进行处理。

         数字转换成字符要加上字符‘0’。字符转换成数字要减去字符'0'。

         因为:字符'0'对应的数值是48,因此字符‘0‘加上数字9正好对应字符'9'。 如char a=9+'0'; a正好是字符'9'。

        

 代码:

       

int reverse(int x) {    double edge=pow(2,31); // (2的31) 至 (2的31-1)        //The minimal integer 2147483648    //if the x is the minimal integer,then its opposite number is     //greater than the greatest,it couldn't be given to the var.    if(x==(-edge))    {        return 0;    }    int var=(x>=0)?x:(-x); //include the =0;     int i=0,j=0,num=0;    int remain=0;    double pre=0;//8 byte        char str[10]={'\0'}; //if not 32,10 is the largest for the decimal number        for(i=0;i<10;i++)    {        remain=var%10+'0'; //% should be the integer        var=var/10;        str[i]=remain;                num++;        if(var==0)        {            break;        }    }        for(j=0;j<num;j++)    {        pre=pre*10+(str[j]-'0');    }        if( (x<0 && (pre>=edge) ) || (x>=0 && ((-pre) < (-edge)) ) )     {        return 0;    }    else    {        int rt=(int)pre;        if(x<0)        {            int rtValue=-rt;            return rtValue;        }        return rt;    }}

  



0 0