LeetCode 69. Sqrt(x)

LeetCode 69. Sqrt(x)
LeetCode 69. Sqrt(x)
出结果的第一反应是,是不是没有人用c写这个问题
LeetCode 69. Sqrt(x)

LeetCode 69. Sqrt(x)

代码倒没什么,二分

#include <stdio.h>
int mySqrt(int x) {
    if (x==1) return 1;
    long start = 0;
    long end = x;
    long last = 0;
    while(start < end) {
        long mid = (start + end) / 2;
        long ret = mid * mid;
        if (ret > x) {
            end = mid;
        } else if(ret < x) {
            start = mid;
        } else {
            return mid;
        }
        if (last == mid) {
            return mid;
        } else {
            last = mid;
        }
    }
    return start;
}
int main() {
    int ret = mySqrt(1);
    printf("ret: %d\n", ret);
}