---
# System prepended metadata

title: Build Week Aug 18 Code Snippets

---

# Build Week Aug 18 Code Snippets

## Implement Square Root
### Python
Brute-force
```
def mySqrt(self, x: int) -> int:
    for i in range(0, x + 1):
        squared = i * i
        if squared == x:
            return i
        elif squared > x:
            return i - 1
    return -1
```

Binary Search
```
def mySqrt(self, x: int) -> int:
    min, max = 0, x
    res = 0
    while min <= max:
        mid = int((min + max) / 2)
        squared = mid * mid
        if squared == x:
            return mid
        elif squared > x:
            max = mid - 1
        else:
            min = mid + 1
            res = mid
    return res
```

### Swift

```
func mySqrt(_ x: Int) -> Int {
  var min = 0, max = x, res = 0
  while min <= max {
    let mid = (min + max) / 2
    let squared = mid * mid
    if squared == x {
      return mid
    } else if squared > x {
      max = mid - 1
    } else {
      min = mid + 1
      res = mid
    }
  }
  return res
}
```