有一个带有java的数学方法的leetcode测试326。三次幂:
public class Solution {
public boolean isPowerOfThree(int n) {
return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
}
}当我打算将这个解决方案转换为Golang时,就像
import "math"
func isPowerOfThree(n int) bool {
return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0
}然后出现编译错误,如下所示
Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)我检查了数学包,但是没有像%操作符那样的受支持的函数,在Golang中有像%这样的有效运算符吗?非常感谢:)
发布于 2020-07-05 14:11:31
TLDR:_, frac := math.Modf(f)
您可以在func Mod(x, y float64) float64包中使用math。
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0
}您也可以使用func Modf(f float64) (int float64, frac float64)。
package main
import (
"math"
)
func isPowerOfThree(n int) bool {
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0
}发布于 2022-08-24 19:27:11
我们不能使用下面的函数,因为在frac中,十进制后可以有一个以上的数字。
_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0因此,要解决这个问题,请使用下面的逻辑
func isPowerOfThree(n int) bool {
quo,_ := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return n == int(math.Pow(3, quo))
} https://stackoverflow.com/questions/62741233
复制相似问题