经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 编程经验 » 查看文章
LeetCode 69. Sqrt(x)
来源:cnblogs  作者:flowingfog  时间:2018/10/20 15:12:59  对本文有异议

分析

难度 易

来源

https://leetcode.com/problems/sqrtx/description/

题目

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

  1. Input: 4
  1. Output: 2

Example 2:

  1. Input: 8
  1. Output: 2
  1. Explanation: The square root of 8 is 2.82842..., and since
  1.              the decimal part is truncated, 2 is returned.
  1. 解答

方法1

  1. 1 package LeetCode;
  2. 2 /*
  3. 3 蛮力,Runtime: 63 ms, faster than 6.02% of Java online submissions for Sqrt(x).
  4. 4 */
  5. 5 public class L69_SqrtX {
  6. 6 public int mySqrt(int x) {
  7. 7 int res=0;
  8. 8 int curSquare=0;//记录上一轮平方数,
  9. 9 int nextSquare=0;
  10. 10 for(int i=0;i<=x/2;i++)
  11. 11 {
  12. 12 nextSquare=(i+1)*(i+1);
  13. 13 if(nextSquare>x||nextSquare<curSquare)//如果平方溢出,一定是大于x的
  14. 14 break;
  15. 15 else{
  16. 16 res++;
  17. 17 curSquare=nextSquare;
  18. 18 }
  19. 19 }
  20. 20 return res;
  21. 21 }
  22. 22
  23. 23 public static void main(String[] args){
  24. 24 L69_SqrtX l69=new L69_SqrtX();
  25. 25 System.out.println(l69.mySqrt(2147395600));
  26. 26 }
  27. 27 }

 

方法2 牛顿法

  1. 1 public int mySqrt (int x) {
  2. 2 if (x <= 1)
  3. 3 return x;
  4. 4 double assume = x / 2;
  5. 5 while (Math.abs(Math.pow(assume, 2) - x) >=1) {
  6. 6 assume = (assume + x/assume) / 2;//求当前值与除以x的结果的均值,故能不断接近平方根
  7. 7 }
  8. 8 return (int) Math.floor(assume);
  9. 9 }

 

方法3 //二分查找

  1. 1 public int mySqrt (int x) {
  2. 2 if (x <= 1)
  3. 3 return x;
  4. 4 int left=1,right=Integer.MAX_VALUE;
  5. 5 int res=0;
  6. 6 while(left<right){
  7. 7 res=left+(right-left)/2;//防止溢出
  8. 8 if(res>x/res){
  9. 9 right=res;
  10. 10 }else{
  11. 11 left=res;
  12. 12 }
  13. 13 if(right-left<=1)
  14. 14 break;
  15. 15 }
  16. 16 return (left+right)/2;
  17. 17 }

 

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号