【小熊刷题】sqrt(x) <Leetcode 69 Java>
2015-09-04 10:05
477 查看
Question
Implement int sqrt(int x).Compute and return the square root of x.
**Difficulty: Medium
https://leetcode.com/problems/sqrtx/
Solution - Binary Search
O(logN)public class Solution { public int mySqrt(int x) { int L = 1; int R = x/2; if(x < 2) return x; while(L <= R){ int M = (L+R)/2; //using divide to avoid overflow if(x / M == M) return M; else if(x / M > M) L = M + 1; else R = M - 1; } return R; } }
Another way is using Newton’s iteration methods: x(i+1) = (x(i) + n/x(i)) / 2 See more details in this link:
/article/6999389.html
相关文章推荐
- 二叉树的遍历 递归非递归 思路和 java实现
- org.eclipse.swt.SWTError:No more Handles
- java中extends和implements的区别
- java设计模式之面向对象思想
- JAVA学习中常用的三种排序
- Java并发编程(你不知道的线程池操作)
- HDOJ2043(JAVAset容器练习)
- eclipse中纯java配置log4j日志
- java模板类以及数组的简单使用
- JAVA中关于set()和get()方法的理解及使用
- 使用maven私服构建 springmvc hibernate4 mysql 项目
- java实现折半插入排序算法
- Ubuntu下搭建Java开发环境
- 主要Java报表工具的比较
- 第一次写博客...
- [Java Concurrency in Practice]第十章 避免活跃性危险
- 规则引擎实战篇-------银行贷款业务处理2
- javaSE基础编程——方法的重载(汽车类)
- javaSE基础编程(九九乘法表)
- 修改Eclipse jdk环境