LeetCode[Math]: Sqrt(x)
来源:互联网 发布:java 动态方法 编辑:程序博客网 时间:2024/05/21 18:44
Implement
int sqrt(int x)
.
Compute and return the square root of x.
这个题目适合用位操作来做,时间和空间复杂度都是O(1)。首先找到根的最高位,然后从最高位开始,依次判断各个位值是否为1。C++代码实现如下:
int sqrt(int x) { int i, j, res = 0; for (i = 0; i < 32; i++) { if ((long)(1<<i) * (1<<i) > x) break; } for (j = i - 1; j >= 0; --j) { long tmp = res | (1 << j); res |= (tmp * tmp <= x) << j; } return res; }
这种解法的时间性能如下图所示:
0 0
- LeetCode[Math]: Sqrt(x)
- [leetcode][math] Sqrt(x)
- LeetCode-69-Sqrt(x) Python要用math.sqrt()
- LeetCode 69 Sqrt(x)(Math、Binary Search)(*)
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [leetcode]Sqrt(x)
- LeetCode-Sqrt(x)
- [leetcode] Sqrt(x)
- banner图片轮转(利用jquery)
- 工作纪要---解决统计差别问题
- iOS-target/action模式,delegate模式
- C++——宏观把控
- 冬令营第一阶段周报--罗双
- LeetCode[Math]: Sqrt(x)
- Junit的各种断言
- 人民日报读书笔记-2015年1月份 国企改革 + 京津冀
- ios-day02(NSBundle的作用、UIImageView和UIButton的区别)
- three.js 源码注释(八十八)extras/GeometryUtils.js
- 山西警方侦破一绑架儿童案
- ios百度地图选择地址返回经纬度
- xampp apache2.4.4 基于域名虚拟主机配置
- awk 使用方法