c语言中sqrt取整,69. Sqrt(x) 求根号再取整

[抄题]:

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:

Input: 4

Output: 2

Example 2:

Input: 8

Output: 2

Explanation: The square root of 8 is 2.82842..., and since

the decimal part is truncated, 2 is returned.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道和二分法有何关系:

找到第一个/最后一个满足某个条件的位置/值,此乃二分法第二重境界

[一句话思路]:

套模板

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

有小数时定义为long型

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

有小数时定义为long型

[复杂度]:Time complexity: O(lgn) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

找到第一个/最后一个满足某个条件的位置/值,此乃二分法第二重境界

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

2b65ef29a5872cc0e4771c25889edd04.gif

6a087676c59fa8b19d76e6bb55a32902.gif

classSolution {public int mySqrt(intx) {//bs

long start = 1, end =x;while (start + 1

start=mid;

}else{

end=mid;

}

}//return end or start

if (end * end <=x) {return (int)end;

}return (int)start;

}

}

View Code

原文:https://www.cnblogs.com/immiao0319/p/8964816.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值