LeetCode —— Sqrt(x)

链接:http://leetcode.com/onlinejudge#question_69

原题:

Implement int sqrt(int x).

Compute and return the square root of x.

思路:测试用例中全是非负数,我是参考百度百科http://baike.baidu.com/view/239903.htm

一个古老的算法,原理很简单(A*10+B)^2=(A*10)^2+2(A*10)*B+B^2=(A^2)*100+(20A+B)*B。

平方过程倒过来,就是开方了。据说还是《九章算术》上的方法,太给力了。

代码:

class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (x <= 0)
            return 0;
        stack<int> s;
        while (x) {
            s.push(x%100);
            x /= 100;
        }
        
        int root = 0;
        int remain = 0;
        while (!s.empty()) {
            int sum = remain * 100 + s.top();
            s.pop();
            int base = root * 20;
            int x = 0;
            for ( ; x <= 9; x++)
                if ( (base+x) * x > sum )
                    break;
            x--;
            root = root * 10 + x;
            remain = sum - (base+x) * x;
        }
        
        return root;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值