My clean and simple 4ms C solution using recursion


  • 0
    M
    int reverse(int x) {
        long reverse_helper(int num, long acc) {
            return num ? reverse_helper(num/10, acc*10+num%10) : ((acc>2147483647 || acc<-2147483648) ? 0 : acc);}
        return reverse_helper(x, 0);}
    

    The function reverse_helper takes two arguments: the number to be reversed, and an accumulator.
    If the number is 0, then we check if our accumulator overflows or not and return it. If the number is not 0, then we divide it by 10, append the remainder to our accumulator and keep going.


Log in to reply
 

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