Skip to content

69. x 的平方根

69. x 的平方根

代码

javascript
// 69. x 的平方根:https://leetcode.cn/problems/sqrtx/description/
// 输入:x = 4
// 输出:2

export function sqrtx (x) {
  let left = 0
  let right = x
  let res = -1
  while (left <= right) {
    const mid = Math.floor((left + right) / 2)
    const midRes = mid * mid
    if (midRes <= x) {
      res = mid
      left = mid + 1
    } else {
      right = mid - 1
    }
  }
  return res
}
typescript
// 69. x 的平方根:https://leetcode.cn/problems/sqrtx/description/
// 输入:x = 4
// 输出:2

export function sqrtx (x: number): number {
  let left = 0
  let right = x
  let res = -1
  while (left <= right) {
    const mid = Math.floor((left + right) / 2)
    const midRes = mid * mid
    if (midRes <= x) {
      res = mid
      left = mid + 1
    } else {
      right = mid - 1
    }
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { sqrtx } from './typescript.ts'
import { sqrtx as sqrtxJs } from './javascript.js'

test(`sqrtx`, () => {
  expect(sqrtx(4)).toBe(2)
  expect(sqrtx(8)).toBe(2)
})

test(`sqrtxJs`, () => {
  expect(sqrtxJs(4)).toBe(2)
  expect(sqrtxJs(8)).toBe(2)
})