LeetCode 题解(167): Sqrt(x)
来源:互联网 发布:c语言中取反 编辑:程序博客网 时间:2024/06/06 03:04
题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
题解:在 [0, x / 2 + 1] 范围内二分查找。
C++版:
class Solution {public: int mySqrt(int x) { int i = 0; int j = x / 2 + 1; while (i <= j) { long mid = (i + j) / 2; long sq = mid * mid; if (sq == x) return mid; else if ( sq < x) i = mid + 1; else j = mid - 1; } return j; }};
Java版:
public class Solution { public int mySqrt(int x) { int i = 0, j = x / 2 + 1; while(i <= j) { long mid = (i + j) / 2; long sq = mid * mid; if(sq == x) return (int)mid; else if(sq > x) j = (int)(mid) - 1; else i = (int)mid + 1; } return j; }}
Python版:
class Solution: # @param {integer} x # @return {integer} def mySqrt(self, x): if x < 0: return None if x == 0 or x == 1: return x y, z = x / 2 + 1, 0 while z <= y: mid = (y + z) / 2 if mid * mid == x: return mid elif mid * mid > x: y = mid - 1 else: z = mid + 1 return y
0 0
- LeetCode 题解(167): Sqrt(x)
- LeetCode题解:Sqrt(x)
- LeetCode - sqrt 题解
- 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)
- [leetcode] Sqrt(x)
- NSDictionary、NSMutableDictionary的基本用法
- Spark Graphx 构建graph和aggregateMessages聚合消息
- 乐点 Android SDK 积分墙开发者文档
- Fixing the Great Wall
- HDU - 2553 N皇后问题
- LeetCode 题解(167): Sqrt(x)
- 黑马程序员——OC笔记之购票系统应用实践
- 最小生成树之PRIM-O(n^2)
- ViewHolder到底用什么修饰?static?final?static final?
- easy ui datagrid的高度自适应
- 1089. Insert or Merge (25)
- java.sql.SQLException: 无效的列类型 PreparedStatement.setObject
- wpf中ist<T>与ObservableCollection<T>的用法区别
- sox音频处理器