Verified Commit 5fbd69aa authored by asahiocean's avatar asahiocean 🚀
Browse files
parent 988b6208
import Foundation
// 50. Pow(x, n)
// https://leetcode.com/problems/powx-n/
// Discuss: https://vk.cc/c4e4oW
class Solution {
func myPow(_ x: Double, _ n: Int) -> Double {
var x = x, n = n, res = 1.0
if n < 0 { x = 1.0/x ; n = -n }
while n > 0 {
if n % 2 != 0 { res *= x }
x *= x
n /= 2
}
return res
}
}
import XCTest
// Executed 3 tests, with 0 failures (0 unexpected) in 0.005 (0.007) seconds
class Tests: XCTestCase {
let s = Solution()
func test0() {
let res = s.myPow(2.00000, 10)
XCTAssertEqual(res, 1024)
}
func test1() {
let res = s.myPow(2.10000, 3)
XCTAssertEqual(res, 9.261000000000001)
}
func test2() {
let res = s.myPow(2.00000, -2)
XCTAssertEqual(res, 0.25)
}
}
Tests.defaultTestSuite.run()
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment