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.
难度:easy
题目:
实现sqrt.
计算并返回x的开方,x保证非负整。
由于返回的类型是整数,十进制数只返回整数部分。
Runtime: 22 ms, faster than 30.19% of Java online submissions for Sqrt(x).
Memory Usage: 27 MB, less than 99.23% of Java online submissions for Sqrt(x).
class Solution {
public int mySqrt(int x) {
if (0 == x) {
return x;
}
int left = 1, right = x, mid = 0, lastMid = 0;
while (left <= right) {
mid = left + (right - left) / 2;
if (mid > x / mid) {
right = mid - 1;
} else {
left = mid + 1;
lastMid = mid;
}
}
return lastMid;
}
}
原文
https://segmentfault.com/a/1190000018098086
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 69. Sqrt(x)