[Leetcode]Sqrt(x)
2015-12-02 19:31
381 查看
Sqrt(x)
Total Accepted: 74812 Total Submissions: 310770 Difficulty: Medium
Implement int sqrt(int x).
Compute and return the square root of x.
Subscribe to see which companies asked this question
题目很简单,弄清题意。使用二分查找即可,有一点:输入不一定是个完全平方数,如果不是的话取根的下边界整数。
Total Accepted: 74812 Total Submissions: 310770 Difficulty: Medium
Implement int sqrt(int x).
Compute and return the square root of x.
Subscribe to see which companies asked this question
题目很简单,弄清题意。使用二分查找即可,有一点:输入不一定是个完全平方数,如果不是的话取根的下边界整数。
class Solution { public: int mySqrt(int x) { if(x <= 0) return 0; int l = 1,r = x; int mid; while(l <= r){ mid = l + ((r - l) / 2); if(mid > x / mid){ r = mid - 1; } else if(mid < x / mid){ l = mid + 1; } else{ return mid; } } return r; } };
相关文章推荐
- POJ2299 Ultra-QuickSort 归并排序和逆序数,树状数组
- sharesdk分享qq空间-错误码1001
- 【HDU 1005】Number Sequence
- A M字母是什么?
- HTTP Analyzer过滤器使用
- serialVersionUID的作用
- Fedora系统初次安装与配置(兼容win10双系统)
- Android 自定义圆形进度条
- Android之ScrollView滚动布局控件使用以及显示新闻网页
- hibernate.hbm2ddl.auto含义介绍
- Makefile浅析(一)
- 《HTML5与CSS3基础教程》第11、14-16、18章
- 织梦程序的安装方法
- Unity 行为树 Behavior Designer
- C#操作 Access 2013(.accdb)的方法
- 论文技巧
- Can't open the mysql.plugin table. Please run mysql_upgrade to create it
- ListView详解
- Asoc dapm(三) - dapm widgets & dapm kcontrol & dapm route
- 第一篇博客——ACM之路!