Golang浮点数类型中未定义%运算符。

5

有一道LeetCode测试326. 3的幂,使用Java实现了一个数学方法:

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)

我查看了math包,但没有像%运算符那样的支持函数,在Golang中是否有任何有效的类似%的运算符?非常感谢:)


2
你找了多久?也许还要考虑为什么要执行“%1”,并查看它是否仍然需要。 - Marc
2个回答

9

简而言之:_, frac := math.Modf(f)

您可以在math包中使用func Mod(x, y float64) float64

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
}

只有这个解决方案是不可行的,因为frac不仅限于单个小数点。作为进一步的解决方案,我们需要检查func isPowerOfThree(n int) bool { quo,_ := math.Modf((math.Log10(float64(n)) / math.Log10(3))) return n == int(math.Pow(3, quo)) } - Shivani Singhal

0

我们不能仅使用下面的函数,因为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)) 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接