Sep-27-2018

争取每周做五个LeedCode题,定期更新,难度由简到难

Title: Reverse Integer

Description:

Given a 32-bit signed integer, reverse digits of an integer.

Example:

Input: 123
Output: 321

Input: -123
Output: -321

Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows

Difficulty:

Easy

Implement Programming Language:

C#

Answer:

这里要判断他的临界值,两个if条件很明显了
时间复杂度是log(x)
空间复杂度是1
在LeetCode上看很多人用换成Char数组的方式做,其实大同小异,虽然代码简洁,但是系统的API把int转成Char数组的时候应该也有开销,就不一定比直接用数据计算来的快,如果这个数的长度远超于int32/64的话,或许用Char数组是唯一的办法。
更有甚者直接调用String的Reverse方法,我也是醉了。

public static int Reverse(int x)
        {
            int rev = 0;
            while (x != 0)
            {
                int temp = x % 10;
                x /= 10;
                if (rev > int.MaxValue / 10 || (rev == int.MaxValue / 10 && pop > 7)) return 0;
                if (rev < int.MinValue / 10 || (rev == int.MinValue / 10 && pop < -8)) return 0;
                rev = rev * 10 + temp;
            }
            return rev;
        }
Github

你可能感兴趣的:(Sep-27-2018)