50. Pow(x, n)
代码
javascript
// 50. Pow(x, n):https://leetcode.cn/problems/powx-n/description/
// 输入:x = 2, n = 10
// 输出:1024
export function powxN (x, n) {
function dfs (x, n) {
if (n === 0) {
return 1
}
const y = dfs(x, Math.floor(n / 2))
return n % 2 === 0 ? y * y : y * y * x
}
return n >= 0 ? dfs(x, n) : 1 / dfs(x, Math.abs(n))
}
typescript
// 50. Pow(x, n):https://leetcode.cn/problems/powx-n/description/
// 输入:x = 2, n = 10
// 输出:1024
export function powxN (x: number, n: number): number {
function dfs (x: number, n: number): number {
if (n === 0) {
return 1
}
const y = dfs(x, Math.floor(n / 2))
return n % 2 === 0 ? y * y : y * y * x
}
return n >= 0 ? dfs(x, n) : 1 / dfs(x, Math.abs(n))
}
测试代码
ts
import { expect, test } from 'vitest'
import { powxN } from './typescript.ts'
import { powxN as powxNJs } from './javascript.js'
test(`powxN`, () => {
expect(powxN(2, 10)).toBe(1024)
expect(powxN(2, -2)).toBe(0.25)
})
test(`powxNJs`, () => {
expect(powxNJs(2, 10)).toBe(1024)
expect(powxNJs(2, -2)).toBe(0.25)
})