leetcode 53: Sqrt(x)

Sqrt(x)Apr 3 '12

Implement int sqrt(int x).

Compute and return the square root of x.


class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
                // Start typing your Java solution below
        // DO NOT write main() function
        if( x <=0 ) return 0;
        
        unsigned k = (1<< (sizeof(x)*8 -1)/2 );
        int rel = 0;
        while( k>0) {
            rel |= k;
            unsigned t = rel*rel;
            cout<<'$'<<t<<'$';
            if( t > x) {
                rel -= k;
            }
            k >>= 1;
        }
        return rel;
    }
};


posted @ 2013-01-26 05:25  西施豆腐渣  阅读(133)  评论(0编辑  收藏  举报