Sqrtx
我只能想出二分的方法,而且还不一定能写出最简洁的代码。无论刷多少遍,牛顿迭代法我都想不到,莫名有种悲哀的感觉:智力是硬伤啊。就算如此,却还要一遍遍不厌其烦地刷,这才是最悲剧的。多说无益,上代码。
二分:
class Solution {
public:
int sqrt(int x) {
if(x==||x==)
return x;
int left=;
int right=x;
long long mid;
long long val;
long long tmp;
while(left<right){
mid=(left+right)/;
val=mid*mid;
if(val==x)
return mid;
else if(val<x)
left=mid+;
else
right=mid-;
}
tmp=right*right;
if(tmp>x)
return right-;
else
return right;
}
};
牛顿迭代法(java):
public class Solution {
public int sqrt(int x) {
if(x < 0) return -1; // assert(x >= 0);
double n = x;
while(Math.abs(n * n - x) > 0.0001){
n = (n + x / n) / 2;
}
return (int)n;
}
}
Sqrtx的更多相关文章
- leetcode — sqrtx
/** * Source : https://oj.leetcode.com/problems/sqrtx/ * * * Implement int sqrt(int x). * * Compute ...
- [LeetCode] Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...
- leetcode算法分类
利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...
- BUG-FREE-For Dream
一直直到bug-free.不能错任何一点. 思路不清晰:刷两天. 做错了,刷一天. 直到bug-free.高亮,标红. 185,OA(YAMAXUN)--- (1) findFirstDuplicat ...
- leetcode bugfree note
463. Island Perimeterhttps://leetcode.com/problems/island-perimeter/就是逐一遍历所有的cell,用分离的cell总的的边数减去重叠的 ...
- 转载 ACM训练计划
leetcode代码 利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode. ...
- LeetCode题目分类
利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...
- 69. Sqrt(x)
题目: Implement int sqrt(int x). Compute and return the square root of x. 链接: http://leetcode.com/pr ...
- <转>LeetCode 题目总结/分类
原链接:http://blog.csdn.net/yangliuy/article/details/44514495 注:此分类仅供大概参考,没有精雕细琢.有不同意见欢迎评论~ 利用堆栈:http:/ ...
随机推荐
- MySQL环境部署
阅读目录: 1.Windows下安装MySQL 2.Linux下安装MySQL 序章: MySQL是个小型的数据库,用来自己做小项目,做学习练习什么的再适合不过了,不过新手总会被一些莫名奇妙的问题难住 ...
- Cocos2d-x 核心概念 - Node中的重要操作
作为跟类,Node有很多的重要的函数 local childNode = cc.Node:create() --创建节点 node:addChildNode(childNode,0,123) --创建 ...
- mutation annovar
1.annovar 很全面 http://annovar.openbioinformatics.org: 2.http://blog.goldenhelix.com/:
- Scrum Meeting 13-20151221
任务安排 姓名 今日任务 明日任务 困难 董元财 无(数据库) 网络连接框架优化 无 胡亚坤 无(数据库) 优化商品搜索 无 刘猛 无 无 马汉虎 无 无 赖彦俞 无 无 燃尽图 团队照片 暂无 代码 ...
- Scope 安装和使用
Scope 安装和使用 一.安装 1. 软件下载 https://sourceforge.net/projects/cscope/files/ 2. 解压 3. 安装 ./configure --pr ...
- SQLite 事务
SQLite数据库是支持事务的,事务的特性可以保证让一系列的操作要么全部完成要么一个都不会完成. 一.调用SQLDatabase的beginTransaction()开起一个事务,当事务处理完成,调用 ...
- 非标准JSON解析
http://blog.csdn.net/superit401/article/details/51734591 String category = "{'v-soft-list':[{ty ...
- Spring的注解
Action想使用serviceImpl时,都需要最原始的方法New一个接口,Service service = new serviceImpl();去实例化service了.都需要Action主动创 ...
- js制作简单的计算器
学着做了一个简单的计算器!记录记录!哈哈 <!DOCTYPE html> <html> <head> <title>简单的计算器</title&g ...
- C++ 指向成员函数指针问题
成员函数指针与常规指针不同,一个指向成员变量的指针并不指向一个内存位置.通常最清晰的做法是将指向数据成员的指针看作为一个偏移量. class ru_m { public: typedef int (r ...