反转数字的执行时间

问题描述 投票:0回答:1

借助 while 循环,反转数字是一项简单的任务,假设数字是 var num = 123 我们创建一个 while 循环,例如 - while num != 0.... {//代码} 这段代码适用于正整数和负整数

但是当我解决leet代码问题时我使用

当 num > 0 {//代码}

所以问题是,在我的 leetCode 提交中,第一个同时适用于负数和正数的 while 循环需要 8 毫秒,而只适用于正整数的 while 循环正如我提到的下面的代码需要 0 毫秒执行为什么...... ?

执行时间较短的第一种方法

class Solution {
func reverse(_ x: Int) -> Int {
        var temp = x
        var result = 0
        var bool = false
        if temp < 0 {
            temp = temp * -1
            bool = true
        }
        while temp > 0 {
            let dig = temp % 10
            result = result*10 + dig
            temp /= 10
        }
        if result >= Int32.min && result <= Int32.max {
            if bool {
                return result * -1
            } else {
            return result
        }
        } else {
            return 0
        }
    }
}

第二种方法执行时间更长

class Solution {
    func reverse(_ x: Int) -> Int {
        var temp = x
        var result = 0
        while temp != 0 {
            let dig = temp % 10
            result = result*10 + dig
            temp /= 10
        }
        if result >= Int32.min && result <= Int32.max {
            return result
        }
        else {
            return 0
        }
    }
}
swift time-complexity reversing
1个回答
0
投票

为什么不直接这样做呢?

func reverse(_ number: Int) -> Int {
    // Grab the sign (+/- of the number). This is -1 for negative,
    // and 1 for positive numbers.
    let sign = number.signum()
    
    // Make a mutable copy of the number that's always positive.
    var number = number * sign

    // To accumulate the result in.
    var result = 0
    
    while number > 0 {
        // Quotient is number / divisor; remainder is number % divisor.
        // Many CPU architectures can do both of these in one operation.
        let (quotient, remainder) = number.quotientAndRemainder(dividingBy: 10)
        // reassign number to number/10
        number = quotient

        // accumulate results
        result *= 10
        result += remainder
    }

    // Multiply by the sign to make negative numbers negative again
    return result * sign
}

在我的测试中,所有三种方法的性能相差不到百分之一,而且我发现这更容易阅读。

完全没有必要做

if negative {multiply by -1}
之类的事情。 总是两个整数相乘比也许有时更快乘以两个整数。

© www.soinside.com 2019 - 2024. All rights reserved.