7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Difficulty: Easy

My submission 1  rt:64ms

public int Reverse(int x) {
           int temp = 1;
            if (x < 0)
            {
                temp = -1;                
            }
            x = x*temp;
            string s = x.ToString();
            s = new string(s.Reverse().ToArray());
            int result;
            if (int.TryParse(s, out result))
            {
                return result*temp;
            }
            return 0;
    }

My submission 2 rt:64ms

 public int Reverse(int x) {
           int result = 0;
            while (x != 0)
            {
                int tail = x%10;
                int newResult = result*10 + tail;
                if((newResult-tail)/10!=result)
                    return 0;
                result = newResult;
                x /= 10;
            }
            return result;  
    }

 

posted @ 2016-07-28 01:14  AshLeakey  阅读(115)  评论(0编辑  收藏  举报