x的平方根
2015-12-14 19:29
197 查看
实现
您在真实的面试中是否遇到过这个题?
Yes
样例
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
挑战
O(log(x))
****************************************
考虑为Integer.MAX_VALUE最大值的情况
复杂度O(log(x))
int sqrt(int x)函数,计算并返回 x 的平方根。
您在真实的面试中是否遇到过这个题?
Yes
样例
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
挑战
O(log(x))
****************************************
考虑为Integer.MAX_VALUE最大值的情况
class Solution { /** * @param x: An integer * @return: The sqrt of x */ public int sqrt(int x) { // write your code here if(x == 0 || x == 1) return x; if(x >= 46340 * 46340) return 46340; int i=0; for(i=0;i<=x/2;i++) { if(i*i > x) { i--; break; } else if(i * i == x) break; } return i; } }
复杂度O(log(x))
int sqrt(int x) { long long i = 0; long long j = x / 2 + 1; while (i <= j) { long long mid = (i + j) / 2; long long sq = mid * mid; if (sq == x) return mid; else if (sq < x) i = mid + 1; else j = mid - 1; } return j; }
相关文章推荐
- ios9基础知识总结(一)
- Oracle 创建用户、表空间,及为索引指定表空间
- storybored 线拖tabbarvc app去保存对象
- [Codevs 1107][NOIP 1107]等效表达
- springbean装配
- 编译Android源码以及单个模块的编译
- kprobe钩子详细介绍
- uva529
- tour
- struts2 helloworld
- Android Studio中常用设置与快捷键
- 对话屏幕Dynpro(se51)
- 108 Convert Sorted Array to Binary Search Tree
- A20csi接口的摄像头模块的移植
- Java 读写Excel
- org.springframework.beans.NotWritablePropertyException
- 大数据时代搜索时的个人隐私
- 自定义纯数字密码输入键盘-仿支付宝数字密码键盘
- iOS 中strong,weak,copy,assign区别
- Opencv学习笔记-常用函数