[leetcode] sqrt(int num)

Implement int sqrt(int x).

Compute and return the square root of x.

TestCases:

 
 
inputoutputexpected 
000
 
111
 
211
 
311
 
422
 
522
 
622
 
722
 
822
 
933
 
1033
 
10243232
 
81929090
 
21473955994633946339
 
21473956004634046340
 
21474836474634046340
   

要注意的问题:

1. sqrt(10)=3

2. int由32bit表示,不可以越界!一般思路:sqrt(x) < x/2, 从0-x/2开始做binary search. 但x>2^16时 (x/2)^2会int溢出。必须设定搜索上限 

class Solution {
public:
    int sqrt(int num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int start=0;
        int end=0;
        int tmp=num;
        int digits=0;
        
        //get the upperbound of its sqrt
        while(tmp > 0)
        {
            digits++;
            tmp=tmp/10;
        }
        for(int i=0;i<(digits+1)/2;i++)
            end=end*10+9;
        if(end > 46340) end=46340; //the largest for 32-bit integer in C++
        if(end > num/2+1 )
             end=(num+1)/2;   
        int med=0;      
        while(start <= end)
        {
            med=(start+end+1)/2;    
            if( med >= 46340)
               return 46340;
            if(med*med <= num && (med+1)*(med+1)>num)
               return med;
            
            if(med*med < num)
                start=med; 
            else
                end=med;
        }
    }
};

思路2: 牛顿搜索: http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number

class Solution {
public:
    int sqrt(int x) {
       
    float n_search_seed=10;
    float num=(float)x;
    float prev_seed=0;
    float EPS = 0.00000001;
    
    do //empiracle 20 loops should be good enough
    {
        prev_seed = n_search_seed;
        n_search_seed=n_search_seed - (n_search_seed*n_search_seed - num)/(2*n_search_seed);
        
    }while(abs(prev_seed - n_search_seed) > EPS);
    
    int result=n_search_seed;
    
    if(result*result > x)
       result--;
    
    return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值