Reverse integer (C 语言)

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Solution:

int reverse(int x) {
    
    long int isNegative = x<0?-1:1;
    long int reversed = 0;
    long num = x * isNegative;
    
    while(num) {
        reversed *= 10;
        reversed += num%10;
        num/=10;
    }
    
    if((isNegative == -1 && reversed > 2147483648) || (isNegative == 1 && reversed > 2147483647 )) {
        return 0;
    }
    
    int ret = (int) reversed * (int)isNegative;

    
    return ret;
}

这个题目和今日 lab 里面的 itoa 比较类似。但是由于 reverse integer 只同样是输出 integer,因此可以把 reversed * 10 后,直接将得到的数字加在reversed后面。

附 itoa:

char* itoa(int num, char result[]) {
    
        long int num2 = num;
        if(num == 0) {
            result[0] = '0';
         } else {
             if(num<0){
             num2 = - (long int)num;
             result[0] = '-';
             long int base = 1;
             int digit = 1;
             while(base<=num2){
                base *= 10;
                digit++;
            }
            result[digit--] = '\0';
            while(num2!=0){
                int last = num2 % 10;
                char temp = last + '0';
                result[digit--] = temp;
                num2 /= 10;
            }
        } else {
            long int base = 1;
            int digit = 1;
            while(base<=num){
                base *= 10;
                digit++;
            }
            digit--;
            result[digit --] = '\0';
            while(num2!=0){
                int last = num2 % 10;
                char temp = last + '0';
                result[digit--] = temp;
                num2 /= 10;
            }
        }
    }
         return result;
}

你可能感兴趣的:(Reverse integer (C 语言))