golang 运算符 % 未在 float64 上定义

H.S*_*.Xu 5 go

有一个 leetcode 测试326。用 java 进行数学方法的三的幂:

public class Solution {
    public boolean isPowerOfThree(int n) {
        return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我打算将此解决方案转换为 Golang Like 时

import "math"

func isPowerOfThree(n int) bool {
    return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0 
}
Run Code Online (Sandbox Code Playgroud)

然后出现编译错误,例如

Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)
Run Code Online (Sandbox Code Playgroud)

我检查了数学包,但没有支持像%运算符这样的函数,是否有像%Golang 中那样的有效运算符?多谢 :)

hyz*_*hyz 9

总而言之: _, 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 
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用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
}
Run Code Online (Sandbox Code Playgroud)