Tuesday, August 4, 2015

突击刷题: sqrt and power



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
    /**
     * @param x: An integer
     * @return: The sqrt of x
     */
    int sqrt(int x) {
        // write your code here
        if (x==0 || x==1)
            return x;
        int beg= 0;
        int end= x;
        while(beg<=end){
            long mid=beg+(end-beg)/2;
            if (mid*mid>x)
                end=mid-1;
            else 
                beg=mid+1;
        }
        return end;
    }
};


No comments:

Post a Comment