鱼C论坛

 找回密码
 立即注册
查看: 2544|回复: 0

[学习笔记] leetcode 69. Sqrt(x)

[复制链接]
发表于 2019-9-16 08:16:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. Implement int sqrt(int x).

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

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

  4. Example 1:

  5. Input: 4
  6. Output: 2
  7. Example 2:

  8. Input: 8
  9. Output: 2
  10. Explanation: The square root of 8 is 2.82842..., and since
  11.              the decimal part is truncated, 2 is returned.
复制代码

  1. class Solution {
  2.     public int mySqrt(int x) {
  3.         long start = 0;
  4.         long mid = 0;
  5.         long end = x;
  6.         
  7.         while(start+ 1 < end){
  8.             
  9.             mid = start + (end - start)/2;
  10.             
  11.             if(mid * mid == x) return (int)mid;
  12.             else if(mid * mid < x) start = mid;
  13.             else end = mid;
  14.         }
  15.         
  16.         if(end * end == x) return (int)end;
  17.         
  18.         return (int)start;
  19.     }
  20. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 14:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表