LeetCode —— Sqrt(x)
2013-04-18 15:24
204 查看
链接:http://leetcode.com/onlinejudge#question_69
原题:
Implement
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。
平方过程倒过来,就是开方了。据说还是《九章算术》上的方法,太给力了。
代码:
原题:
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; } };
相关文章推荐
- Leetcode 69 Sqrt(x) 求x开根号的整数部分
- leetcode之Sqrt(x)
- Leetcode 69 Sqrt(x)
- leetcode - 69.Sqrt(x)
- LeetCode Solutions : Sqrt(x)
- LeetCode-Easy刷题(15) Sqrt(x)
- LeetCode:Sqrt(x)
- LeetCode之Sqrt(x)
- leetcode_069 Sqrt(x)
- LeetCode——Sqrt(x)
- LeetCode——Sqrt(x)
- LeetCode 69. Sqrt(x)
- Leetcode 69. Sqrt(x) 开根号 解题报告
- 【leetcode】Sqrt(x)
- leetcode 第69题 Sqrt(x)
- LeetCode 69. Sqrt(x) 解题报告
- [LeetCode] Sqrt(x)
- Leetcode: Sqrt(x)
- Sqrt(x) -- LeetCode (Java)
- Sqrt(x) LeetCode