Exponentiation operator in Swift

后端 未结 9 1175
天命终不由人
天命终不由人 2020-12-13 22:45

I don\'t see an exponentiation operator defined in the base arithmetic operators in the Swift language reference.

Is there really no predefined integer or float ex

9条回答
  •  猫巷女王i
    2020-12-13 23:38

    If you're specifically interested in the exponentiation operator for Int type, I don't think that existing answers would work particularly well for large numbers due to the way how floating point numbers are represented in memory. When converting to Float or Double from Int and then back (which is required by pow, powf and powl functions in Darwin module) you may lose precision. Here's a precise version for Int:

    let pow = { Array(repeating: $0, count: $1).reduce(1, *) }
    

    Note that this version isn't particularly memory efficient and is optimized for source code size.

    Another version that won't create an intermediate array:

    func pow(_ x: Int, _ y: Int) -> Int {
      var result = 1
      for i in 0..

提交回复
热议问题