Sqrt(x) !!!

Implement int sqrt(int x).

Compute and return the square root of x.

思路:Sqrt(double)需要进行逼近。目前这种方法掌握不好

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;    
            if( t > x) {  
                rel -= k;  
            }  
            k >>= 1;  
        }  
        return rel;  
    }  
}; 

 

posted @ 2013-07-10 22:37  一只会思考的猪  阅读(188)  评论(0编辑  收藏  举报