Tang Tang - 6 months ago 15
Swift Question

Swift isPowerofThree can not pass 243

My project mission is to find out if an integer is power of three. My code can pass 0 ,1, 3,9,27,81 test cases, but 243.
And when I try to print out to debug, I found a weird thing. When I input 243, I print out log3(243), it gives me 5.0, which is correct. But I tried to print log3(243) % 1, it gives me 0.99999999999, which is so weird.

class Solution {
func isPowerOfThree(n: Int) -> Bool
{
//print("log3(n): \(log3(Double(n)))")

if n == 0
{
return true
}

if n == 1
{
return true
}

//print("weird here: \(log3(Double(n)) % 1)" )

if log3(Double(n)) % 1 == 0.0
{

return true
}
//print("log3: \(log3(Double(n)))")
//print("floor log3: \(floor(log3(Double(n))))")
//print("log3: \(Int(log3(Double(n))))")
return false
}

func log3(val: Double) -> Double
{
return log(val)/log(3.0)
}

}

var test = Solution()
var result = test.isPowerOfThree(243)
print(result)

Answer

This is due to the precision of Double. Numbers a coded in binary format and at some point the precision you expect can't reached.

I tried your program and log3(243) give me 4.9999999... So it make sense the modulo 1 fail.

If you change Double to Float, your program will works.

if log3(Float(n)) % 1 == 0.0

func log3(val: Float) -> Float
Comments