forked from lexrus/LeetCode.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
326.swift
50 lines (40 loc) · 1.13 KB
/
326.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// 326.swift
// LeetCode
//
// Created by Lex on 1/15/16.
// Copyright © 2016 Lex Tang. All rights reserved.
//
import Foundation
import XCTest
/*
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
*/
infix operator ^^ { }
func ^^ (radix: Int, power: Int) -> Double {
return pow(Double(radix), Double(power))
}
// @see https://leetcode.com/discuss/79400/o-1-python-solution-with-explanation
extension Double {
func isPowerOf(num: Int) -> Bool {
if self < Double(num) {
return false
}
let a = log(Double(self)) / log(Double(num))
return fabs(round(a) - a) < 0.0000000000001
}
}
class PowerOfThreeTest: XCTestCase {
func testPowerOfThree() {
XCTAssert(Double(9).isPowerOf(3))
XCTAssert((3 ^^ 30).isPowerOf(3))
XCTAssert((3 ^^ 78).isPowerOf(3))
XCTAssert(!(2 ^^ 27).isPowerOf(3))
XCTAssert((3 ^^ 99).isPowerOf(3))
XCTAssert((3 ^^ 333).isPowerOf(3))
XCTAssert((2 ^^ 27).isPowerOf(2))
XCTAssert(!Double(2).isPowerOf(3))
}
}