LeetCode: Reverse Integer

    xiaoxiao2021-03-25  75

    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.

    Subscribe to see which companies asked this question.*

    解题过程 : 如果输入的是负数,我们先将他化为正数,最后再加上负号,将整数每个位置上的值都按顺序添加到一个数组中,然后用数组将他倒转,要保证倒转后的值不溢出,加一个判断溢出的条件就可以了,代码如下:

    int reverse(int x) { int s[32]; int i = 0; int flag = 0; if(x<0){ x = -x; flag = 1; } while(x>0){ s[i] = x % 10; x = (x - s[i]) / 10; i++; } long long y = 0; for(int j=0; j<i; j++ ){ y = s[j] * pow(10,i-j-1) + y; } if(y>2147483648 ){ return 0;} if(flag == 0) return y; else return -y; }
    转载请注明原文地址: https://ju.6miu.com/read-35598.html

    最新回复(0)