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:/ ...
随机推荐
- kegg-kass注释--转载
在注释KEGG的时候,一直用到kaas,具体kaas是个什么东东,简单的总结一下吧. KEGG是由日本人搞的一个代谢图,收录基因和基因组的数据库,数据库可以分为 3大部分,基因数据库, 化学分 ...
- session、cookie
session:全局变量组 存放位置:存放在服务器上 用法:相当于一个变量的使用方法,存在于服务器内存上,抓取速度快 主界面: using System; using System.Collectio ...
- mysql mybatis-generator plugin 分页
generator.xml配置如下: plugin必须紧跟context,否则会报错 <?xml version="1.0" encoding="UTF-8&quo ...
- String or binary data would be truncated 解决办法
原因: 一般出现这个问题是因为数据库中的某个字段的长度小,而插入数据大 解决: 找到相应字段,修改表结构,使表字段大小相同或大于要插入的数据
- centos下php安装swoole扩展
官网:http://wiki.swoole.com/wiki/index/prid-1 国内Git镜像:http://git.oschina.net/matyhtf/swoole.git 下载源码后, ...
- MySQL FUNCTION 整理
-- 返回最后一个INSERT查询中, AUTO_INCREMENT列设置的第一个表的值. SELECT LAST_INSERT_ID();
- MySQL问题记录--python插入中文至MySQL提示SQLErroor:1366错误
一.在爬虫脚本做以下操作仍提示错误:SQL Error: 1366: Incorrect string value: "\xd0\xc2\xce\xc5-" for column ...
- 十天精通CSS3学习笔记 part2
第6章 征服CSS3选择器(上) 属性选择器 在HTML中,通过各种各样的属性可以给元素增加很多附加的信息.例如,通过id属性可以将不同div元素进行区分. 在CSS2中引入了一些属性选择器,而CSS ...
- Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules
解决方案: 找到如下文件 将"jst.web"的version改低一些
- SPI 驱动分析
断更博客两个月后我又回来了,眯着躺倒就能睡熟的小眼睛,在这儿敲键盘.这篇文章给你快乐,你有没有爱上我! SPI驱动由三部分组成,分别为drivers.core.device.通过bus总线连接.困了不 ...