C# solution


  • 0
    public class Solution {
        public int Reverse(int x) {
            
            bool isNeg = x < 0;
            if(isNeg)
            {
              x = x * -1;
            }
            
             string reverse = "";
            string xString = x.ToString();
            for(int i=xString.Length - 1; i>=0; i--)
            {
                reverse+=xString[i].ToString();
            }
            
            if(isNeg)
            {
                reverse = reverse.Insert(0, "-");
            }
            
            try
            {
            return Convert.ToInt32(reverse);
            }
            catch
            {
                return 0;
            }
        }
    }
    
    

  • 0

    For C#, why not using "checked" keyword?

    my AC code:

        public int Reverse(int x) {
            try
            {
                int result = 0;
                while(x!=0)
                {
                    result = checked( result * 10 + x % 10);
                    x = x / 10;
                }
                return result;
            }
            catch(Exception)
            {
                return 0 ;
            }
        }
    

Log in to reply
 

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