What is the Kotlin exponent operator

后端 未结 5 658
春和景丽
春和景丽 2021-01-07 17:33

What is the exponent operator in Kotlin. I assumed it would be ** but it seems to throw up an error in my code.

when (pendingOperation) {
    \"         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 17:43

    As other answers have mentioned there is no exponent operator in Kotlin/Java. However, it is not advisable to use the extension function available in Double and Float for performing exponentiation of Long. Here's why: Conversion of Double back to Long after exponentiation can lead to rounding of number due to precision limits of Double.

    val EXP = 38
    
    println(3.toDouble().pow(EXP).toLong())
    // 1350851717672992000
    
    println(3.toDouble().pow(EXP))
    // 1.350851717672992E18 
    

    But the actual answer was 1350851717672992089. Thus, I'd advise you to use BigIntegers to perform exponentiation. The same can also be used for fast modulo exponentiation. Here's our final pow(base, exp) function:

    fun pow(n: Long, exp: Int): Long{
        return BigInteger.valueOf(n).pow(exp).toLong()
    }
    

提交回复
热议问题