I always get "1" as result. :(
Whats wrong with this function?
def power(base: Int, exp: Int): BigInt = {
def _power(result: BigInt, exp: Int): BigInt = exp match {
case 0 => 1
case _ => _power(result*base, exp-1)
}
_power(1, exp)
}
您必须替换为: case 0 => result
probably not relevant for OP but I used this answer as an example for something and this version works:
def power(base: Int, exp: Int): BigInt = {
def _power(result: BigInt, exp: Int): BigInt = exp match {
case 0 => 1
case 1 => result
case _ => _power(result*base, exp-1)
}
_power(base, exp)
}
Better, tail-recursive solution (stack-safe) may look like:
def power(base: Int, exp: Int): BigInt {
@scala.annotation.tailrec
def loop(x: BigInt, n: Long, kx: BigInt): BigInt = {
if (n == 1) x * kx
else {
if (n % 2 == 0)
loop(x * x, n / 2, kx)
else
loop(x, n - 1, x * kx) // O(log N) time complexity!
}
}
if (n == 0) 1
else {
val pow = loop(base, Math.abs(exp.toLong), 1)
if (n > 0) pow else 1 / pow
}
}
I'm new to Scala and I had the same task, liked the idea with match . Used your code as an example and this is what I've got
def power(base: Int, exp: Int): BigDecimal = {
if (exp == 0) 1 else {
@tailrec
def _power(result: BigDecimal, exp: Int): BigDecimal = exp match {
case 0 => result
case pos if (pos > 0) => _power(result * base, exp - 1)
case neg if (neg < 0) => _power(result / base, exp + 1)
}
_power(1, exp)
}
}
Don't know what @tailrec means yet but I guess it may be useful, IDEA hinted me with that:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.