Calculating powers of integers

前端 未结 16 2070
情书的邮戳
情书的邮戳 2020-12-08 06:18

Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a

16条回答
  •  猫巷女王i
    2020-12-08 06:43

    When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent

    example:

    22 = 1 << 2 = (int) Math.pow(2, 2)
    210 = 1 << 10 = (int) Math.pow(2, 10)

    For larger exponents (over 31) use long instead

    232 = 1L << 32 = (long) Math.pow(2, 32)

    btw. in Kotlin you have shl instead of << so

    (java) 1L << 32 = 1L shl 32 (kotlin)

提交回复
热议问题