C# Solution Using Recursion


  • 0
    R
    public class Solution {
        public int Reverse(int n) 
        {
                long nAbs = Math.Abs((long)n);
    
                long res = 0;
                ReverseIntRec(nAbs, ref res);
    
                if (n < 0)
                {
                    res = res * (-1);
                }
    
                return (res > int.MaxValue || res < int.MinValue) ? 0 : (int)res;
        }
        
        public static int ReverseIntRec(long n, ref long res)
            {
                if (n < 10)
                {
                    res = n % 10;
                    return 0;
                }
    
                int power = ReverseIntRec(n / 10, ref res);
                ++power;
    
                res += (long)((n % 10) * Math.Pow(10, power));
                return power;
            }
    }
    

Log in to reply
 

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