2 Solutions in C


  • 0
    H

    This solution is done by simple arithmetic and for some reason took me awhile to figure out.

    int reverse(int num) {
        // Test for number out of range or zero
        if ((num > 2147483647) || (num < -2147483648) || (num == 0))
        {
            return 0;
        }
    
        long reversed = 0;
        while (num != 0)
        {
            reversed = (reversed * 10) + (num % 10);
            num /= 10;
        }
    
        // Is reversed number bigger than 32 bit int?
        if ((reversed > 2147483647) || (reversed < -2147483648))
        {
            return 0;
        }
    
        return (int)reversed;
    }
    

    This was my first solution and seemed more intuitive even though it requires a lot more manipulation. This reverses it by manipulating a character array. The arithmetic solution is much more elegant and efficient.

    int reverse(int num)
    {
        printf("num     : %d\n", num);
    
        // Test for number out of range or zero
        if ((num > 2147483647) || (num < -2147483648) || (num == 0))
        {
            return 0;
        }
    
        // Change in to char array and null array
        char numBuf[20];
        for (int i = 0; i < 20; i++) { numBuf[i] = '\0'; }
        sprintf(numBuf, "%d", num);
    
        // Count numbers and get length
        int charLen = 0;
        while (numBuf[charLen] != '\0') { charLen++; }
    
        // Brute force reverse
        char hold[charLen + 1];
        hold[charLen] = '\0';
        for (int i = 0, j = (charLen - 1); i < charLen; i++, j--)
        {
            if (numBuf[i] == '-')
            {
                hold[0] = numBuf[i];
                j++;
            }
            hold[j] = numBuf[i];
        }
    
        // Check reversed number is in range
        if (charLen == 10 || (charLen == 11 && numBuf[0] == '-'))
        {
            long test = atol(hold);
            if ((test > 2147483647) || (test < -2147483648) || (test == 0))
            {
                return 0;
            }
        }
        return (atoi(hold));
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.