链接: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;
}
};