leetcode

Reverse Integer solution using TypeScript

Below is my TypeScript solution to the LeetCode "Reverse Integer" question.

Time Complexity: Because each iteration divides the input by 10, the time complexity is O(log10(n)) where n is the inputted value.

Space Complexity: The following approach uses a constant amount of space, making the space complexity O(1).

/**
 * Given a 32-bit signed integer, reverse digits of an integer.
 * If the given number overflows, return 0.
 *
 * Time Complexity: O(log10(n))
 * Space Complexity: O(1)
 *
 * Input: 123
 * Output: 321
 *
 * Input: -123
 * Output: -321
 */
function reverse(x: number): number {
    let result = 0;

    // if input is negative, make result negative
    const multiplier = x < 0 ? -1 : 1;
    
    // number of digits: 6789 = 4
    const digits = Math.floor(Math.log10(Math.abs(x)));
                                       
    for (let i = 0; i <= digits; i++) {
        // create a mask: 2345 = 1000, 345 = 100
        const mask = Math.floor(Math.pow(10, digits - i));
        
        // get the last digit: 1234 = 4
        const last = Math.abs(x) % 10;
        
        // multiple the last digit by most significant place
        result += last * mask;     
        
        // trim the last digit: 1234 = 123
        x = Math.floor(Math.abs(x) / 10);
    }
    
    // 32-bit signed integer overflow results in 0 
    if (result > 2**31) {
        return 0;
    } else {
        return result * multiplier;    
    }
}

more LeetCode posts